create a struct with a field of type slice in go

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.go
type Person struct {
    Name     string
    Age      int
    Friends  []string
}
82 chars
6 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.go
// Create a new Person
p := Person{
    Name: "Alice",
    Age:  30,
    Friends: []string{"Bob", "Charlie"},
}

// Access the Person's Friend field
fmt.Println(p.Friends) // output: [Bob Charlie]
197 chars
10 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