使用Golang填充字符串数组模型

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

golang filling a string array model

问题

我无法弄清楚如何填充下面简单模型的数组字符串。我尝试过的方法也已经给出。如何填充数组字符串"Alternate"?

func main() {
    type Person struct {
        FirstName string   `json:"FirstName,omitempty"`
        LastName  string   `json:"Lastname,omitempty"`
        Age       string   `json:"Age,omitempty"`
        Alternate []string `json:"Alternate,omitempty"`
    }

    p1 := Person{FirstName: "Rajeev", LastName: "Singh", Age: "27", Alternate: ["Samantha Holder"]}

    fmt.Println(p1)
}
英文:

I cant figure out a way to fill the array string of the below simple model. What I have tried is also give. How do I fill the array string "Alternate"?

func main() {
	type Person struct {
		FirstName string   `json:"FirstName,omitempty"`
		LastName  string   `json:"Lastname,omitempty"`
		Age       string   `json:"Age,omitempty"`
		Alternate []string `json:"Alternate,omitempty"`
	}

	p1 := Person{FirstName: "Rajeev", LastName: "Singh", Age: "27", Alternate: ["Samantha Holder"]}

	fmt.Println(p1)
}

答案1

得分: 1

使用复合字面量

p1 := Person{
	FirstName: "Rajeev",
	LastName:  "Singh",
	Age:       "27",
	Alternate: []string{"Samantha Holder"},
}

https://play.golang.com/p/zm9Dpx3th48

英文:

Use a composite literal.

p1 := Person{
	FirstName: "Rajeev",
	LastName:  "Singh",
	Age:       "27",
	Alternate: []string{"Samantha Holder"},
}

https://play.golang.com/p/zm9Dpx3th48

huangapple
  • 本文由 发表于 2022年2月26日 19:58:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/71276431.html
匿名

发表评论

匿名网友

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

确定