I'm trying to iterate over a slice of strings and add 10 to each string, e.g:
package main
import "fmt"
func addTen(ss *[]string) {
for _, s := range *ss {
s = fmt.Sprintf("%s10", s)
}
}
func main() {
ss := []string{"a", "b", "c"}
addTen(&ss)
fmt.Println(ss)
}
The compiler is complaining that s
is not defined.
Use this code to append "10" to each slice element:
package main
import "fmt"
func addTen(ss []string) {
for i, s := range ss {
ss[i] = fmt.Sprintf("%s10", s)
}
}
func main() {
ss := []string{"a", "b", "c"}
addTen(ss)
fmt.Println(ss)
}
Key points:
s = fmt.Sprintf("%s10", s)
assigns to local variable s
, which is discarded.