尝试将一个结构体添加到结构体数组中(使用golang)

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

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

type Fruit struct {
	name   string
	color  string
	weight float32
}

func newFruit(name string) (string, string, float32) {
	return name, &quot;unk&quot;, 0
}

func main() {
	var basket [3]Fruit 
	var name string

	for i := 0; i &lt; len(basket); i++ {
		fmt.Print(&quot;Enter name: &quot;)
		fmt.Scanln(&amp;name)
		basket[i] := newFruit(name) //&lt;-- error: assignment mismatch, tried &quot;=&quot; but still not working
	}

	for i := 0; i &lt; len(basket); i++ {
		fmt.Println(&quot;Name: &quot;, i, &quot;: &quot;, basket[i].name)
		fmt.Println(&quot;Color: &quot;, i, &quot;: &quot;, basket[i].color)
		fmt.Println(&quot;Weight: &quot;, i, &quot;: &quot;, 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: &quot;unk&quot;, 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)

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

发表评论

匿名网友

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

确定