2013-11-26 33 views
8

我正在學習Go,並且我製作了這個簡單而粗略的庫存程序,只是爲了修補結構和方法來了解它們的工作方式。在驅動程序文件中,我嘗試從收銀員類型的項目映射中調用方法和項目類型。我的方法有指針接收器直接使用結構而不是複製。當我運行程序我得到這個錯誤.\driver.go:11: cannot call pointer method on f[0] .\driver.go:11: cannot take the address of f[0]在Golang中解引用地圖索引

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.godriver.go中的打印語句

回答

12

正如沃爾克在他回答說 - 你不能在地圖上得到一個項目的地址。你應該做的 - 是存儲指針的項目在你的地圖,而不是存儲項值:

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

0

而其他的答案是有用的,我覺得在這種情況下,最好是剛做非變異函數不是取指針:

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

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