V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
Verizon
V2EX  ›  Go 编程语言

请教一下这句代码的作用

  •  
  •   Verizon · 2022-06-21 17:21:00 +08:00 · 1038 次点击
    这是一个创建于 675 天前的主题,其中的信息可能已经有所发展或是发生改变。

    components 是一个参数,类型是[]string ,不知道第四行代码的作用是干啥的。。 求教一下

    1	if len(components) == 0 {
    2 	  components = []string{":" + verb}
    3	} else {
    4 	  components = append([]string{}, components...)
    5  	 components[len(components)-1] += ":" + verb
    6	}
    
    Ritter
        1
    Ritter  
       2022-06-21 17:25:09 +08:00
    deep copy 么
    molly2mollyzyz
        2
    molly2mollyzyz  
       2022-06-21 17:26:19 +08:00
    拷贝对象?
    zwpaper
        3
    zwpaper  
       2022-06-21 17:43:42 +08:00   ❤️ 1
    得结合上下文,目测是为了复制出来一份 components ,以免影响到函数调用方的 components
    Verizon
        4
    Verizon  
    OP
       2022-06-21 17:45:50 +08:00
    @zwpaper 感谢,没往这方面想
    zwpaper
        5
    zwpaper  
       2022-06-21 17:49:05 +08:00
    但是我还有点疑惑,下面是还会给 components 增加内容吗?为啥不用 copy ?
    Verizon
        6
    Verizon  
    OP
       2022-06-21 18:12:46 +08:00
    @zwpaper 下面有很多读取 components 的操作,应该是为了不影响读取吧
    https://stackoverflow.com/questions/27055626/concisely-deep-copy-a-slice
    zwpaper
        7
    zwpaper  
       2022-06-21 18:38:36 +08:00
    copy 也不影响读取,看你发的 so 的 benchmark ,append 性能不输 copy ,append 代码会简洁些,也许是这个考虑
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2860 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:11 · PVG 23:11 · LAX 08:11 · JFK 11:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.