小编典典

在Golang中解引用地图索引

go

我目前正在学习Go,我制作了这个简单而又粗糙的库存程序,只是为了修改结构和方法以了解它们的工作原理。在驱动程序文件中,我尝试从Cashier类型的项目映射中调用方法和项目类型。我的方法具有指针接收者,可以直接使用结构而不是进行复制。当我运行程序时,出现此错误.\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())
}

真正与我的问题有关的代码部分是中的GetAmount函数inventory.go和print语句driver.go


阅读 322

收藏
2020-07-02

共1个答案

小编典典

地图条目无法寻址(因为其地址可能会在地图增长/缩小期间发生变化),因此您无法在其上调用指针接收器方法。

此处详细信息:https :
//groups.google.com/forum/?fromgroups=#!topic/ golang-nuts/
4_pabWnsMp0

2020-07-02