0

hoping you can help below is a concise version of my code.

basically im passing an array of structs to floatInSlice() in which either a new struct gets added to the array or an existing struct AudienceCategory.Sum gets ++

all is generally working fine except for the b.Sum = b.Sum+1

Now I know that if I want to pass an obect as a pointer rather than value I need to use */& but I just cant seem to get it working, any help much appriciated!

type AudienceCategory struct {
    Cat int
    Sum int
}


var counter = []AudienceCategory{}


func main() {
     for i := 1; i < len(words); i++ {
         counter = floatInSlice(category,counter)
        if counter != nil{}
     }
     fmt.Printf("%v ", counter) 
}


func floatInSlice(category int, counter *[]AudienceCategory) []AudienceCategory {
    for _, b := range counter {
        if b.Cat == category {
            b.Sum = b.Sum+1

            return counter
        }
    }
    x := AudienceCategory{Cat:category,Sum:1}
    counter = append( counter, x)
    return counter
}

EDIT *******

got it working in the end thanks for the help guys

func floatInSlice(category int, counter []AudienceCategory) []AudienceCategory {

    for i := 0; i < len(counter); i++ {
        if counter[i].Cat == category {
            counter[i].Sum = counter[i].Sum+1

            return counter
        }
    }
    x := AudienceCategory{Cat:category,Sum:1}
    counter = append( counter, x)
    return counter
}
Aaron Kenny
  • 321
  • 1
  • 5
  • 14

1 Answers1

1

When you use value range as in _, b := range counter, b contains a copy of each element of counter. So you are summing a copy that is lost, not the element in the slice.

You should use

func floatInSlice(category int, counter *[]AudienceCategory) []AudienceCategory {
    for i, b := range *counter {
        if b.Cat == category {
            (*counter)[i].Sum = (*counter)[i].Sum+1

            return counter
        }
    }
    x := AudienceCategory{Cat:category,Sum:1}
    counter = append( counter, x)
    return counter
}
siritinga
  • 4,063
  • 25
  • 38
  • many thx siritinga but im getting the below errors..... ./readfile.go:83: cannot use counter (type []AudienceCategory) as type *[]AudienceCategory in argument to floatInSlice ./readfile.go:147: cannot range over counter (type *[]AudienceCategory) ./readfile.go:151: cannot use counter (type *[]AudienceCategory) as type []AudienceCategory in return argument ./readfile.go:155: first argument to append must be slice; have *[]AudienceCategory ./readfile.go:156: cannot use counter (type *[]AudienceCategory) as type []AudienceCategory in return argument – Aaron Kenny Sep 11 '14 at 19:02
  • cannot range over counter (type *[]AudienceCategory) – Aaron Kenny Sep 11 '14 at 19:16