我有一个接收字符串的函数,并检查该字符串是否存在于其他字符串的列表中。很简单。
func (s *Foo) validateCurrency(currency string) error {
for _, currency := range s.Config.Currencies {
if currency.Name() == currency {
return nil
}
}
return ErrCurrencyNotFound
}这是Currency结构:
type Currency struct {
name string
// ...
}
func (c *Currency) Name() string {
return c.name
}然而,我似乎收到了这样的错误:
无效操作: currency.Name() ==货币(不匹配类型string和*config.Currency)
为什么围棋编译器对我大喊大叫?我不明白..。两者都是字符串。currency.Name()返回一个字符串。为什么错误说它返回一个*config.Currency
发布于 2018-04-10 22:20:55
在for循环中跟踪currency。查看这段代码可以获得一个简单的示例:https://play.golang.org/p/UFmwqQ4JZtG
第一次分配给currency -> func (s *Foo) validateCurrency(currency string) error {
第二项与第一项相形见绌的任务:-> for _, currency := range s.Config.Currencies {
为修复更改其中一个变量名。
发布于 2018-04-10 22:21:28
您的for循环定义了一个名为currency类型的Currency变量。您的函数有一个参数,也称为currency,但类型为string。这导致currency在for循环中看到在循环中定义的Currency类型的currency的值,而不是函数的参数。
简而言之,您有两个名为currency的变量,但只能访问最近定义的一个变量。
要解决这个问题,您应该将一个currency变量重命名为其他变量。
https://stackoverflow.com/questions/49763593
复制相似问题