user2671513
user2671513

Reputation:

Go, Golang : traverse through 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?

Upvotes: 10

Views: 32514

Answers (2)

nemo
nemo

Reputation: 57599

The range keyword works only on strings, array, slices and channels. So, no it is not possible to iterate over structs with range. But you supply a slice, so that's not a problem. The problem is the type defenition of the function. You write:

func GetTotalWeight(data_arr []struct) int

Now ask yourself: what type did I request here?

Everything starting with [] indicates a slice, so we deal with a slice of struct. But what type of struct? The only way to match ever struct would be to use interface values. Otherwise you'd need to give an explicit type, for example TrainData.

The reason why this is an syntax error is, that the only time the language allows the struct keyword is on defining a new struct. A struct definition has the struct keyword, followed by a { and that's why the compiler tells you that he expects the {.

Example for struct definitions:

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

Upvotes: 1

Christian Ternus
Christian Ternus

Reputation: 8492

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

Upvotes: 18

Related Questions