去吧, golang : traverse through struct

标签 go

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 {

是否可以遍历结构体?

最佳答案

您的功能几乎完全正确。您想将 TrainData 定义为 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

关于去吧, golang : traverse through struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439430/

相关文章:

linux - 使用 GoLang 自动化 `mysql_secure_installation`

golang + Godeps : Adding new dependency override Godeps. json文件

来自其他包的 golang 结构

unit-testing - 使用 PanicsWithValue 进行 Golang 单元测试

java - protoc-gen-java代码使用Inline对象提示语法错误

go - Go Imaginary Literals 的最佳用途是什么?

go - 我可以在 Golang 中将变量类型与 .(type) 进行比较吗?

go - 如何在 Go 中初始化大小为 N 的空 bytes.Buffer?

go - 错误还是功能? Golang中 'range'和 'channel'相关的垃圾回收

go - 使用 golang 将 DSA key 解析为 tls 配置对象