【问题标题】:Golang slice append doesn't copy the value? [closed]Golang slice append 不复制值? [关闭]
【发布时间】:2021-08-28 13:17:13
【问题描述】:

我是 Golang 的新手,我有以下代码 sn-p 和下面的输出,这让我很困惑。我期待append 将字符串复制到切片而不是替换它?所以我的预期输出应该是[[one] [two]] 为什么不这样做?

Playground Link

type StringList []interface{}
type GlobalStringList []StringList

var globalStringList GlobalStringList
var stringList StringList

myString := "one"
stringList = append(stringList, myString)
globalStringList = append(globalStringList, stringList)

stringList[0] = "two"
globalStringList = append(globalStringList, stringList)

fmt.Print(globalStringList)

// Output
// [[two] [two]]

【问题讨论】:

标签: go append slice


【解决方案1】:

不清楚为什么要使用接口切片,也不清楚为什么要使用接口切片。您似乎在添加毫无意义的复杂性。

此外,对于这样一个简单的示例,您的变量名称过长。一旦您的程序增长,您当然希望有描述性的名称,但这里不是这种情况。这是本质上相同的程序,但没有接口类型:

package main
import "fmt"

func main() {
   var a, b []string
   a = append(a, "one")
   b = append(b, a...)
   a[0] = "two"
   b = append(b, a...)
   fmt.Println(b) // [one two]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2017-11-12
    • 1970-01-01
    • 2020-12-31
    • 2021-07-17
    • 2020-09-23
    • 2020-06-23
    相关资源
    最近更新 更多