[英]How to build a map of struct and append values to it using GO?
I tried many ways to build a map of struct and append values to it and I did not find any way to do it. 我尝试了许多方法来构建struct映射并向其附加值,但没有找到任何方法。
The keys of the map are strings. 地图的键是字符串。 The struct is made of two parts : "x" integer and "y" a slice of strings.
该结构由两部分组成:“ x”整数和“ y”字符串切片。
The errors I face to build the map are (for m) : main.go:11: syntax error: unexpected comma, expecting semicolon, newline, or }
我在构建地图时遇到的错误是(for m):
main.go:11: syntax error: unexpected comma, expecting semicolon, newline, or }
When I try to add new keys and values to the map, the errors are : go:33: syntax error: missing operand
当我尝试向地图添加新的键和值时,错误为:
go:33: syntax error: missing operand
Thank you very much to help me find the mistakes ! 非常感谢您帮助我发现错误!
package main
import "fmt"
type TEST struct {
x int
y []string
}
// none of these var gives the expected result
var m = map[string]*struct{x int, y []string}{"foo": {2, {"a", "b"}}, }
var m2 = map[string]struct{x int, y []string}{"foo": {2, {"a", "b"}}, }
var n = map[string]*struct{x int
y []string
}{"foo": {2, {"a", "b"}}, }
var o = map[string]*struct{
x int
y []string
}{"foo": {2, {"a", "b"}}, }
func main() {
m["foo"].x = 4
fmt.Println(m["foo"].x)
// how can I had a new key ?
m["toto"].x = 0
m["toto"] = {0, {"c", "d"}}
// and append the string "e" to {"c", "d"} ?
m["toto"].y = append(m["toto"].y, "e")
a := new(TEST)
a.x = 0
a.y = {"c", "d"}
m["toto"] = a
fmt.Println(m)
}
Here's a way to write it: 这是一种编写方法:
package main
import "fmt"
type TEST struct {
x int
y []string
}
var m = map[string]*TEST { "a": {2, []string{"a", "b"}} }
func main() {
a := new(TEST)
a.x = 0
a.y = []string{"c", "d"}
m["toto"] = a
fmt.Println(m)
}
Note: two types aren't the same just because their struct have identical fields. 注意:两种类型不一样,只是因为它们的结构具有相同的字段。
Long story. 很长的故事。 If you for some reason prefer unnamed types you must be quite verbose in composite literal describing both types and values
如果出于某种原因您更喜欢未命名的类型,则您在描述类型和值的复合文字中必须非常冗长
var m = map[string]*struct {
x int
y []string
}{"foo": {2, []string{"a", "b"}}}
or with semicolons 或带有分号
var m = map[string]*struct {x int; y []string}{"foo": {2, []string{"a", "b"}}}
and without indirection 并且没有间接
var m1 = map[string]struct {
x int
y []string
}{2, []string{"a", "b"}}}
To add new key 添加新密钥
m["todo"] = &struct {
x int
y []string
}{0, []string{"c", "d"}}
You can also assign TEST struct but only without indirection because pointers *TEST and *youunnamedstruct are not assignable nevertheless structs having identical fields assignable themself 您还可以分配TEST结构,但只能分配无间接值,因为指针* TEST和* youunnamedstruct不可分配,但是具有相同字段可自行分配的结构
m1["todo"] = TEST{0, []string{"c", "d"}}
You can append only to indirect map struct field 您只能附加到间接映射结构字段
m["todo"].y = append(m["todo"].y, "e")
because direct map struct fields are not addressable 因为直接映射结构字段不可寻址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.