可以,你可以在Golang中创建一个包含切片成员的结构体。

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

Golang - can I have a struct with slice member?

问题

在Go语言中,结构体的成员可以是切片。要在结构体中定义一个切片成员,可以使用切片类型作为结构体的字段类型。例如:

  1. type MyStruct struct {
  2. MySlice []int
  3. }

在上面的示例中,MySlice 是一个整数切片,它是 MyStruct 结构体的一个成员。你可以根据需要在结构体中定义其他类型的切片成员。

希望这可以帮助到你!如果你有其他问题,请随时问。

英文:

Is it possible to have a slice as a member of struct in Go? If so, how do I do it?

答案1

得分: 8

你可以选择使用切片(slice)或者在运行时定义固定大小的数组。

  1. package main
  2. import "fmt"
  3. func main() {
  4. mystruct := struct {
  5. array [3]int
  6. slice []int
  7. }{
  8. [...]int{1, 2, 3},
  9. []int{1, 2, 3, 4, 5},
  10. }
  11. fmt.Println(mystruct)
  12. }

请注意,这是一个Go语言的代码示例,用于演示如何在结构体中同时使用数组和切片。

英文:

you can have a slice or you can have a fixed size array defined at runtime

package main

  1. import "fmt"
  2. func main() {
  3. mystruct := struct {
  4. array [3]int
  5. slice [] int
  6. }{
  7. [...]int{1, 2, 3},
  8. []int{1, 2, 3, 4, 5},
  9. }
  10. fmt.Println(mystruct)
  11. }

huangapple
  • 本文由 发表于 2014年7月12日 07:51:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/24708178.html
匿名

发表评论

匿名网友

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

确定