2013-11-26 8 views
8

私は現在、Goを学習しています。このシンプルで粗在庫のプログラムは、構造とメソッドを使ってどのように動作するかを理解するだけです。ドライバファイルでは、キャッシャータイプのアイテムマップからアイテムタイプとアイテムタイプを呼び出そうとします。私のメソッドは、コピーを作成するのではなく、構造体を直接使うためのポインタ・レシーバを持っています。私はプログラムを実行すると、私はこのエラーを取得する.\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の場合

答えて

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 
}