Golang – 创建结构体数组?

huangapple go评论77阅读模式
英文:

Golang - Create 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() {
	// 在这里输入你的代码。从标准输入读取输入,将输出打印到标准输出
	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}
	}
}
英文:

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 &quot;fmt&quot;

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(&amp;n)
	for i := 0; i &lt; n; i++ {
		var namez string
		var numberz int
		fmt.Scanln(&amp;namez)
		fmt.Scanln(&amp;numberz)
		list[i] = person{name: namez, age: numberz}

	}

}

答案1

得分: 5

你在这里使用了切片而不是数组,所以你需要向切片中添加元素。

var list []person 是一个切片。

切片示例:

package main

import "fmt"

type person struct {
    name string
    age  int
}

var n int
var p person
var list []person

func main() {
    // 在这里输入你的代码。从标准输入读取输入,将输出打印到标准输出
    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})

    }

}

你也可以使用数组,但你需要用元素的数量进行初始化。

更多信息请参考:https://go.dev/blog/slices-intro

英文:

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 &quot;fmt&quot;

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(&amp;n)
    for i := 0; i &lt; n; i++ {
        var namez string
        var numberz int
        fmt.Scanln(&amp;namez)
        fmt.Scanln(&amp;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

huangapple
  • 本文由 发表于 2022年3月10日 11:52:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/71418636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定