create a struct with a field of type array in go

To create a struct with a field of type array in Go, define a struct and the field that will contain an array of a specific type, along with the length of the array.

Here's an example of a struct that has a field of type array:

main.go
type Person struct {
    Name    string
    Address [2]string
}
64 chars
5 lines

In the above example, the Person struct has two fields - Name of type string and Address of type array [2]string. The Address field has a length of 2, meaning it can store 2 string values.

To instantiate an object of this struct and set its values, you can use the following code:

main.go
person := Person{
    Name: "John",
    Address: [2]string{"123 Main St", "Apt 4C"},
}
87 chars
5 lines

In the above code, an instance of the Person struct is created and its Name and Address fields are set to "John" and an array of strings containing "123 Main St" and "Apt 4C", respectively.

related categories

gistlibby LogSnag