Перейти - добавить к фрагменту в структуре
Я пытаюсь реализовать две простые структуры следующим образом:
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))
}
Что я делаю неправильно? Я просто хочу вызвать метод addItem в структуре ящика и передать элемент в
Ответы
Ответ 1
Хм... Это самая распространенная ошибка, которую люди делают при добавлении к ломтикам в Go. Вы должны вернуть результат на срез.
func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {
box.Items = append(box.Items, item)
return box.Items
}
Кроме того, вы определили тип AddItem
для *MyBox
, поэтому вызовите этот метод как box.AddItem(item1)
Ответ 2
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))
}
Игровая площадка
Вывод:
1