遍历字符串切片,并向每个字符串添加10

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:

  • Assign the string to the slice element. The code s = fmt.Sprintf("%s10", s) assigns to local variable s, which is discarded.
  • The code in this answer passes a slice value instead of passing a pointer to a slice. It's not necessary to pass a pointer in this situation, nor is there a performance benefit to passing a pointer. It's simpler to just pass the value.