dtwvr26066 2013-11-26 17:55
浏览 37
已采纳

在Golang中解引用地图索引

I'm learning Go currently and I made this simple and crude inventory program just to tinker with structs and methods to understand how they work. In the driver file I try to call a method from and item type from the items map of the Cashier type. My method have pointer reciever to use the structs directly instead of making copies. When I run the program I get this error .\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 := item{name, amount}
    index := len(c.items)
    c.items[index] = temp
}

func (c *Cashier) GetItems() map[int]item{
    return c.items;
}

func (i *item) GetName() string{
    return i.itemName
}

func (i *item) GetAmount() int{
    return i.amount
}

Driver.go:

package main

import "fmt"
import "inventory"

func main() {
    x := inventory.Cashier{}
    x.AddItem("item1", 13)
    f := x.GetItems()

    fmt.Println(f[0].GetAmount())
}

The part of the code that really pertains to my problem is the GetAmount function in inventory.go and print statement in the driver.go

  • 写回答

3条回答 默认 最新

  • douxiong0668 2013-11-26 18:16
    关注

    A map entry cannot be addressed (as its address might change during map growth/shrink), so you cannot call pointer receiver methods on them.

    Detail here: https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/4_pabWnsMp0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题