我正在尝试编写一个函数来修改由指针传递的原始地图,但 Go 不允许这样做。假设我有一张大地图,不想来回复制。
使用按值传递的代码正在运行并且正在执行我需要的操作,但涉及按值传递(操场):
package main
import "fmt"
type Currency string
type Amount struct {
Currency Currency
Value float32
}
type Balance map[Currency]float32
func (b Balance) Add(amount Amount) Balance {
current, ok := b[amount.Currency]
if ok {
b[amount.Currency] = current + amount.Value
} else {
b[amount.Currency] = amount.Value
}
return b
}
func main() {
b := Balance{Currency("USD"): 100.0}
b = b.Add(Amount{Currency: Currency("USD"), Value: 5.0})
fmt.Println("Balance: ", b)
}
但是,如果我尝试像这里(操场)那样将参数作为指针传递:
func (b *Balance) Add(amount Amount) *Balance {
current, ok := b[amount.Currency]
if ok {
b[amount.Currency] = current + amount.Value
} else {
b[amount.Currency] = amount.Value
}
return b
}
我收到编译错误:
prog.go:15: invalid operation: b[amount.Currency] (type *Balance does not support indexing)
prog.go:17: invalid operation: b[amount.Currency] (type *Balance does not support indexing)
prog.go:19: invalid operation: b[amount.Currency] (type *Balance does not support indexing)
我该如何处理?
慕尼黑的夜晚无繁华
POPMUISE
相关分类