2013-08-04 26 views
16

Tôi cố gắng để thực hiện cấu trúc 2 đơn giản như sau:Go - append để cắt trong struct

package main 

import (
    "fmt" 
) 

type MyBoxItem struct { 
    Name string 
} 

type MyBox struct { 
    Items []MyBoxItem 
} 

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem { 
    return append(box.Items, item) 
} 

func main() { 

    item1 := MyBoxItem{Name: "Test Item 1"} 
    item2 := MyBoxItem{Name: "Test Item 2"} 

    items := []MyBoxItem{} 
    box := MyBox{items} 

    AddItem(box, item1) // This is where i am stuck 

    fmt.Println(len(box.Items)) 
} 

am i làm gì sai? Tôi chỉ đơn giản muốn gọi phương thức addItem trên struct hộp và vượt qua một mục trong

Trả lời

27

Hmm ... Đây là phổ biến nhất sai lầm mà mọi người thực hiện khi thêm vào các lát trong Go. Bạn phải gán kết quả lại cho slice.

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem { 
    box.Items = append(box.Items, item) 
    return box.Items 
} 

Ngoài ra, bạn đã xác định AddItem cho *MyBox loại, vì vậy gọi phương pháp này như box.AddItem(item1)

+0

Bạn phải gán kết quả trở lại lát, chính xác những gì tôi đã không làm. Cảm ơn – Raf

9
package main 

import (
     "fmt" 
) 

type MyBoxItem struct { 
     Name string 
} 

type MyBox struct { 
     Items []MyBoxItem 
} 

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem { 
     box.Items = append(box.Items, item) 
     return box.Items 
} 

func main() { 

     item1 := MyBoxItem{Name: "Test Item 1"} 

     items := []MyBoxItem{} 
     box := MyBox{items} 

     box.AddItem(item1) 

     fmt.Println(len(box.Items)) 
} 

Playground


Output:

1