英文:
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 "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
得分: 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 "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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论