dt3358 2018-12-24 19:32
浏览 85
已采纳

遍历字符串切片,并向每个字符串添加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.

  • 写回答

1条回答 默认 最新

  • dsztc99732 2018-12-24 20:06
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器