我正在学习Go目前,我制作了这个简单粗暴的库存程序,只是为了修改结构和方法来理解它们是如何工作的.在驱动程序文件中,我尝试从Cashier类型的items map中调用方法from和item type.我的方法有指针接收器直接使用结构而不是复制.当我运行程序时,我收到此错误.\driver.go:11: cannot call pointer method on f[0]
.\driver.go:11: cannot take the address of f[0]
Inventory.go:
package inventory
type item struct{
itemName string
amount int
}
type Cashier struct{
items map[int]item
cash int
}
func (c *Cashier) Buy(itemNum int){
item, pass := c.items[itemNum]
if pass{
if item.amount == 1{
delete(c.items, itemNum)
} else{
item.amount--
c.items[itemNum] = item
}
c.cash++
}
}
func (c *Cashier) AddItem(name string, amount int){
if c.items == nil{
c.items = make(map[int]item)
}
temp := …Run Code Online (Sandbox Code Playgroud) 我的go程序中定义了以下对
type pair struct {
a float64
b float64
}
Run Code Online (Sandbox Code Playgroud)
然后我创建一个地图:
dictionary map[string]pair
Run Code Online (Sandbox Code Playgroud)
我先添加一个元素:
dictionary["xxoo"] = pair{5.0, 2.0}
Run Code Online (Sandbox Code Playgroud)
然后我试着这样做:
dictionary["xxoo"].b = 5.0 // try to change from 2.0 to 5.0
Run Code Online (Sandbox Code Playgroud)
最后一行没有编译,它说"不能分配给它"
我想知道这是什么原因?