gogoogle-app-engine-golang

Golang - Create Array of Struct?


How to create an array of struct with user input ?

I am trying to create a loop that will get input from user for a struct and add it into an array of struct

package main

import "fmt"

type person struct {
    name string
    age  int
}

var n int
var p person
var list []person

func main() {
    //Enter your code here. Read input from STDIN. Print output to STDOUT
    fmt.Scanln(&n)
    for i := 0; i < n; i++ {
        var namez string
        var numberz int
        fmt.Scanln(&namez)
        fmt.Scanln(&numberz)
        list[i] = person{name: namez, age: numberz}

    }

}

Solution

  • You have used a slice instead of an array here, so you would need to append to the slice.

    var list []person is a slice.

    Slice e.g:

    package main
    
    import "fmt"
    
    type person struct {
        name string
        age  int
    }
    
    var n int
    var p person
    var list []person
    
    func main() {
        //Enter your code here. Read input from STDIN. Print output to STDOUT
        fmt.Scanln(&n)
        for i := 0; i < n; i++ {
            var namez string
            var numberz int
            fmt.Scanln(&namez)
            fmt.Scanln(&numberz)
            list = append(list, person{name: namez, age: numberz})
    
        }
    
    }
    

    You can use an array too, you would need to initialize it with the number of elements.

    More here: https://go.dev/blog/slices-intro