加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Go,Golang:遍历struct

发布时间:2020-12-16 19:03:56 所属栏目:大数据 来源:网络整理
导读: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 { 是
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定义为类型,并将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!",2000},{"I feel very good about its food and atmosphere.",{"The location is very accessible.",1500},{"One of the best cities I've ever been.",{"Definitely want to visit again.",{"I do not like this area.","neg",500},{"I am tired of this city.",700},{"I can't deal with this town anymore.",300},{"The weather is terrible.",{"I hate this city.",100},{"I won't come back!",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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读