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 {

是否可以遍历结构?

4

2 回答 2

18

您的功能几乎完全正确。您想将 TrainData 定义为 a type,并将类型签名更改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
于 2013-10-18T00:18:50.497 回答
1

range关键字仅适用于字符串、数组、切片和通道。所以,不,不可能用range. 但是你提供一个切片,所以这不是问题。问题是函数的类型定义。你写:

func GetTotalWeight(data_arr []struct) int

现在问问自己:我在这里要求的是什么类型的?

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

这是语法错误的原因是,该语言唯一允许struct关键字是在定义新结构时。结构定义具有 struct 关键字,后跟 a {,这就是编译器告诉您他期望{.

结构定义示例:

a := struct{ a int }{2} // anonymous struct with one member
于 2013-10-18T00:28:04.860 回答