在Golang中取消引用地图索引

时间:2013-11-26 17:55:32

标签: pointers go

我正在学习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 := 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函数和driver.go

中的print语句

3 个答案:

答案 0 :(得分:22)

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

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

答案 1 :(得分:14)

正如Volker在他的回答中所说 - 你无法获得地图中某个项目的地址。你应该做的是 - 存储指向地图中项目的指针,而不是存储项目值:

package main

import "fmt"

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.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
}

func main() {
    x := Cashier{}
    x.AddItem("item1", 13)
    f := x.GetItems()
    fmt.Println(f[0].GetAmount()) // 13
    x.Buy(0)
    f = x.GetItems()
    fmt.Println(f[0].GetAmount()) // 12
}

http://play.golang.org/p/HkIg668fjN

答案 2 :(得分:1)

虽然其他答案很有用,但我认为在这种情况下,最好只使非变异函数取指针:

date