Go,Golang: 遍历结构体

10
我想遍历一个结构体数组。 http://play.golang.org/p/fJACxhSrXX
 func GetTotalWeight(data_arr []struct) int {
    total := 0
    for _, elem := range data_arr {
        total += elem.weight
    }
    return total
 }

但是我遇到了语法错误

   syntax error: unexpected ), expecting {

能否遍历结构体?

2个回答

18

你的函数几乎完全正确。你想将TrainData定义为一个类型,并将GetTotalWeight的类型签名更改为[]TrainData,而不是[]struct,像这样:

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

1
"range关键字仅适用于字符串、数组、切片和通道。因此,不可能使用range迭代结构体。但是,您可以提供一个切片,这样就不是问题了。问题在于函数的类型定义。 您写道:"
func GetTotalWeight(data_arr []struct) int

现在问问自己:我在这里请求了什么类型?

[]开头的所有内容都表示一个切片,因此我们处理的是一个结构体切片。 但是,什么类型的结构体呢?唯一匹配每个结构体的方法是使用接口值。否则,您需要给出明确的类型,例如TrainData

之所以会出现语法错误,是因为语言只允许在定义新结构体时使用struct关键字。结构体定义有结构体关键字,后跟{,这就是编译器告诉您他期望{的原因。

结构体定义示例:

a := struct{ a int }{2} // anonymous struct with one member

1
你可以使用反射来迭代结构体。 - Druska
1
你可以获取结构体字段并对它们进行迭代。但是,你不能使用 range 直接迭代结构体,这就是关键所在。 - nemo
1
是的,只是发布一些额外的信息,让正在寻找答案的人看到。 - Druska

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接