Golang,开始:穿过结构
我想遍历一个结构数组Golang,开始:穿过结构,go,Go,我想遍历一个结构数组 func GetTotalWeight(data_arr []struct) int { total := 0 for _, elem := range data_arr { total += elem.weight } return total } 但我得到了语法错误 syntax error: unexpected ), expecting { 是否可以遍历结构?您的函数几乎完全正确。您希望将TrainDat
func GetTotalWeight(data_arr []struct) int {
total := 0
for _, elem := range data_arr {
total += elem.weight
}
return total
}
但我得到了语法错误
syntax error: unexpected ), expecting {
是否可以遍历结构?您的函数几乎完全正确。您希望将TrainData定义为
类型
,并将GetTotalWeight
的类型签名更改为[]TrainData
,而不是[]结构
,如下所示:
import "fmt"
type TrainData struct {
sentence string
sentiment string
weight int
}
var TrainDataCity = []TrainData {
{"I love the weather here.", "pos", 1700},
{"This is an amazing place!", "pos", 2000},
{"I feel very good about its food and atmosphere.", "pos", 2000},
{"The location is very accessible.", "pos", 1500},
{"One of the best cities I've ever been.", "pos", 2000},
{"Definitely want to visit again.", "pos", 2000},
{"I do not like this area.", "neg", 500},
{"I am tired of this city.", "neg", 700},
{"I can't deal with this town anymore.", "neg", 300},
{"The weather is terrible.", "neg", 300},
{"I hate this city.", "neg", 100},
{"I won't come back!", "neg", 200},
}
func GetTotalWeight(data_arr []TrainData) int {
total := 0
for _, elem := range data_arr {
total += elem.weight
}
return total
}
func main() {
fmt.Println("Hello, playground")
fmt.Println(GetTotalWeight(TrainDataCity))
}
运行此命令将提供:
Hello, playground
13300
range
关键字仅适用于字符串、数组、切片和通道。因此,不可能使用范围
在结构上迭代。但是你提供一片,所以这不是问题。问题在于函数的类型定义。
你写道:
func GetTotalWeight(data_arr []struct) int
现在问问你自己:我在这里要求的是什么类型的
以[]
开头的所有内容都表示一个切片,因此我们处理的是结构的切片。
但是什么类型的结构?匹配ever struct的唯一方法是使用
接口值。否则,您需要给出一个显式类型,例如
列车数据
这是语法错误的原因是,该语言只允许
struct
关键字用于定义新结构。结构定义具有
struct关键字,后跟一个{
,这就是为什么编译器告诉您他需要
{
结构定义示例:
a := struct{ a int }{2} // anonymous struct with one member
您可以使用reflect迭代结构您可以获取结构字段并对其进行迭代,是的。但是,您不能简单地使用
range
迭代结构,这就是要点,只需为搜索答案的用户发布一些额外信息即可