【发布时间】:2016-07-27 14:13:29
【问题描述】:
我正在尝试编写一个函数来修改通过指针传递的原始地图,但 Go 不允许这样做。假设我有一张大地图,不想来回复制。
使用按值传递的代码正在工作并且正在做我需要但涉及按值传递的代码 (playground):
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)
}
但是如果我尝试像这里一样将参数作为指针传递(playground):
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)
我该如何处理?
【问题讨论】:
标签: go pass-by-reference