英文:
Trying to add a struct to an array of struct (golang)
问题
要求是将一个函数中的结构体的“实例”添加到主函数中的结构体数组中。我尝试使用“append”函数,但它不能用于数组。我还尝试使用切片方法(append)和指针,但只是让我的代码变得更糟。我应该能够访问三个水果(结构体)数组中的所有元素以进行输出。谢谢!
package main
import "fmt"
type Fruit struct {
name string
color string
weight float32
}
func newFruit(name string) Fruit {
return Fruit{name: name, color: "unk", weight: 0}
}
func main() {
var basket [3]Fruit
var name string
for i := 0; i < len(basket); i++ {
fmt.Print("Enter name: ")
fmt.Scanln(&name)
basket[i] = newFruit(name)
}
for i := 0; i < len(basket); i++ {
fmt.Println("Name:", i, ":", basket[i].name)
fmt.Println("Color:", i, ":", basket[i].color)
fmt.Println("Weight:", i, ":", basket[i].weight)
}
}
英文:
The requirement is to add an "instance" of a struct from a function to be added to an array of struct in the main. I tried using "append" but it won't work on an array. I tried using slice method (append) and also pointers but it just made my code worst. I should be able to access all the elements in the array of three fruits (of structs) for output. Thanks!
package main
import "fmt"
type Fruit struct {
name string
color string
weight float32
}
func newFruit(name string) (string, string, float32) {
return name, "unk", 0
}
func main() {
var basket [3]Fruit
var name string
for i := 0; i < len(basket); i++ {
fmt.Print("Enter name: ")
fmt.Scanln(&name)
basket[i] := newFruit(name) //<-- error: assignment mismatch, tried "=" but still not working
}
for i := 0; i < len(basket); i++ {
fmt.Println("Name: ", i, ": ", basket[i].name)
fmt.Println("Color: ", i, ": ", basket[i].color)
fmt.Println("Weight: ", i, ": ", basket[i].weight)
}
}
答案1
得分: 2
你的newFruit
函数需要返回一个Fruit
对象,而不是两个字符串和一个float32。
例如:
func newFruit(name string) Fruit {
return Fruit{name: name, color: "unk", weight: 0}
}
正如@mkopriva在评论中指出的,你还有一个拼写错误:
basket[i] := newFruit(name) // 错误的写法
应该改为
basket[i] = newFruit(name)
英文:
Your newFruit
needs to return a Fruit
rather than two strings and a float32.
For example:
func newFruit(name string) Fruit {
return Fruit{name: name, color: "unk", weight: 0}
}
As @mkopriva points out in the comments, you also have a typo:
basket[i] := newFruit(name) // WRONG
should be
basket[i] = newFruit(name)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论