dongxie3701 2013-10-18 00:09
浏览 613
已采纳

Go,Golang:遍历struct

http://play.golang.org/p/fJACxhSrXX

I want to traverse through an array of structs.

 func GetTotalWeight(data_arr []struct) int {
    total := 0
    for _, elem := range data_arr {
        total += elem.weight
    }
    return total
 }

But I am getting syntax error

   syntax error: unexpected ), expecting {

Is it possible to traverse through structs?

  • 写回答

2条回答 默认 最新

  • dslfq06464 2013-10-18 00:18
    关注

    Your function is almost entirely correct. You want to define TrainData as a type, and change the type signature of GetTotalWeight to []TrainData, not []struct, like so:

    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))
    }
    

    Running this gives:

    Hello, playground
    13300
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘