英文:
First argument to append must be slice; have struct - golang map
问题
无法在这种情况下使用append
。任何帮助将不胜感激。
append
的第一个参数必须是切片:
package main
import (
"fmt"
)
type C struct {
value5 string
value6 string
}
type B struct {
value3 string
value4 C
}
type A struct {
value1 string
value2 B
}
type X struct {
key int
}
func main() {
letSee := map[X]A{}
letSee[X{1}] = A{"T", B{"T1", C{"T11", "T12"}}}
letSee[X{1}] = append(letSee[X{1}], A{"L", B{"L1", C{"L11", "L12"}}})
fmt.Println(letSee)
}
链接:https://play.golang.org/p/R4gDO9MPBS
英文:
Can't seem to use append
for this case. Any help would be appreciated.
First argument to append
must be slice:
package main
import (
"fmt"
)
type C struct {
value5 string
value6 string
}
type B struct {
value3 string
value4 C
}
type A struct {
value1 string
value2 B
}
type X struct{
key int
}
func main() {
letSee := map[X]A{}
letSee[X{1}]=A{"T",B{"T1",C{"T11","T12"}}}
letSee[X{1}]=append(letSee[X{1}], A{"L",B{"L1",C{"L11","L12"}}})
fmt.Println(letSee)
}
答案1
得分: 2
如果你想在地图中存储与同一个键相关联的多个值,那么值的类型必须适合这种情况。结构体不适合,但slice是一个完美的选择。
所以将你的值类型改为[]A
:
letSee := map[X][]A{}
letSee[X{1}] = []A{A{"T", B{"T1", C{"T11", "T12"}}}}
letSee[X{1}] = append(letSee[X{1}], A{"L", B{"L1", C{"L11", "L12"}}})
fmt.Printf("%+v", letSee)
输出结果(在Go Playground上尝试):
map[{key:1}:[{value1:T value2:{value3:T1 value4:{value5:T11 value6:T12}}}
{value1:L value2:{value3:L1 value4:{value5:L11 value6:L12}}}]]
英文:
If in a map you want to store multiple values associated with the same key, the value type must be suitable for that. A struct isn't, but a slice is a perfect choice.
So change your value type to []A
:
letSee := map[X][]A{}
letSee[X{1}] = []A{A{"T", B{"T1", C{"T11", "T12"}}}}
letSee[X{1}] = append(letSee[X{1}], A{"L", B{"L1", C{"L11", "L12"}}})
fmt.Printf("%+v", letSee)
Output (try it on the Go Playground):
map[{key:1}:[{value1:T value2:{value3:T1 value4:{value5:T11 value6:T12}}}
{value1:L value2:{value3:L1 value4:{value5:L11 value6:L12}}}]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论