First argument to append must be slice; have struct – golang map

huangapple go评论90阅读模式
英文:

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)
}

https://play.golang.org/p/R4gDO9MPBS

答案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}}}]]

huangapple
  • 本文由 发表于 2017年6月11日 14:25:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44480989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定