简体   繁体   中英

Golang edit array of struts from main() to function

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM