To create a struct with a field of type slice in Go, you can define the field using square brackets []
followed by the data type of the elements in the slice. Here is an example:
main.go82 chars6 lines
In this example, the Person
struct has a field called Friends
, which is defined as a slice of strings ([]string
). This field will hold a variable number of friends for each Person
instance.
You can then create and use a Person
object like this:
main.go197 chars10 lines
In this example, we create a new Person
object called p
and initialize its fields. The Friends
field is initialized with a slice literal containing two strings. We can then access the Friends
field using p.Friends
.
gistlibby LogSnag