3

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}

    }

}
1
  • I would also recommend you add the error and other things that might be helpful here. Commented Mar 10, 2022 at 3:58

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.