Home > Net >  Golang - Create Array of Struct?
Golang - Create Array of Struct?

Time:03-11

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}

    }

}

CodePudding user response:

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

  • Related