我试图实现2个简单的结构如下:
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))
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我只想在box结构上调用addItem方法并传入一个项目
Shu*_*hya 50
嗯......这是人们在Go中附加切片时最常犯的错误.您必须将结果分配回切片.
func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {
box.Items = append(box.Items, item)
return box.Items
}
Run Code Online (Sandbox Code Playgroud)
此外,您已AddItem为*MyBox类型定义,因此请将此方法称为box.AddItem(item1)
zzz*_*zzz 12
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))
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
Run Code Online (Sandbox Code Playgroud)
arj*_*era 11
虽然这两个答案都很好。还有两个变化可以做,
package main
import (
"fmt"
)
type MyBoxItem struct {
Name string
}
type MyBox struct {
Items []MyBoxItem
}
func (box *MyBox) AddItem(item MyBoxItem) {
box.Items = append(box.Items, item)
}
func main() {
item1 := MyBoxItem{Name: "Test Item 1"}
item2 := MyBoxItem{Name: "Test Item 2"}
box := MyBox{}
box.AddItem(item1)
box.AddItem(item2)
// checking the output
fmt.Println(len(box.Items))
fmt.Println(box.Items)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48268 次 |
| 最近记录: |