golang array of objects

2023-05-08by@timqian&@ChatGPT.Model: gpt-3.5
timqian

golang array of objects

Avatar
Avatar

In Go, you can create an array of objects by defining a struct and then declaring an array of that struct type.

Here is an example:

type Person struct {
    Name string
    Age  int
}

func main() {
    people := [2]Person{
        {Name: "Alice", Age: 25},
        {Name: "Bob", Age: 30},
    }

    fmt.Println(people)
}

In this example, we define a struct Person with two fields Name and Age. Then, we declare an array of Person with length 2 and initialize it with two Person objects.

To access the elements of the array, you can use indexing:

alice := people[0]
fmt.Println(alice.Name) // Output: Alice

bob := people[1]
fmt.Println(bob.Age) // Output: 30