[英]How to build a map of struct and append values to it using GO?
我尝试了许多方法来构建struct映射并向其附加值,但没有找到任何方法。
地图的键是字符串。 该结构由两部分组成:“ x”整数和“ y”字符串切片。
我在构建地图时遇到的错误是(for m): main.go:11: syntax error: unexpected comma, expecting semicolon, newline, or }
当我尝试向地图添加新的键和值时,错误为: go:33: syntax error: missing operand
非常感谢您帮助我发现错误!
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)
}
这是一种编写方法:
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)
}
注意:两种类型不一样,只是因为它们的结构具有相同的字段。
很长的故事。 如果出于某种原因您更喜欢未命名的类型,则您在描述类型和值的复合文字中必须非常冗长
var m = map[string]*struct {
x int
y []string
}{"foo": {2, []string{"a", "b"}}}
或带有分号
var m = map[string]*struct {x int; y []string}{"foo": {2, []string{"a", "b"}}}
并且没有间接
var m1 = map[string]struct {
x int
y []string
}{2, []string{"a", "b"}}}
添加新密钥
m["todo"] = &struct {
x int
y []string
}{0, []string{"c", "d"}}
您还可以分配TEST结构,但只能分配无间接值,因为指针* TEST和* youunnamedstruct不可分配,但是具有相同字段可自行分配的结构
m1["todo"] = TEST{0, []string{"c", "d"}}
您只能附加到间接映射结构字段
m["todo"].y = append(m["todo"].y, "e")
因为直接映射结构字段不可寻址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.