登录
首页 >  Golang >  Go问答

两种不同的“切片复制”方法是如何不同的?

来源:stackoverflow

时间:2024-02-28 23:12:26 257浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《两种不同的“切片复制”方法是如何不同的?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

那么,为什么它们(下面的 no.1 和 no.2)不同?

type T1 struct {
    local []string
}

func (t *T1) Assign(param ...string) {
    t.local = nil
    t.local = append(t.local, param...) // No.1 <<<
    t.local = param[:]                  // No.2 <<<
}

它们不同的,当然:no.2 相当“浅薄”。

当更改 t.local[i] 时,如果使用 no.2,她将导致原始字符串出现乱码。


解决方案


您的“no.1”方法附加到 nil 切片,保证如果提供的参数超过零,将分配新的支持数组。

您的“no.2”方法不会创建新切片,它只是对参数进行切片。

如果通过传递现有切片来调用 assign(),则第二种方法将存储该切片,并且如果修改其元素,则会反映在存储的切片中。

让我们稍微修改一下您的示例来测试它:

type t1 struct {
    local []string
}

func (t *t1) assign1(param ...string) {
    t.local = nil
    t.local = append(t.local, param...) // no.1 <<<
}

func (t *t1) assign2(param ...string) {
    t.local = nil
    t.local = param[:] // no.2 <<<
}

测试它:

t1 := &t1{}

s := []string{"a", "b", "c"}
t1.assign1(s...)
fmt.println(t1.local)
s[0] = "x"
fmt.println(t1.local)

s = []string{"a", "b", "c"}
t1.assign2(s...)
fmt.println(t1.local)
s[0] = "x"
fmt.println(t1.local)

输出(在 Go Playground 上尝试):

[a b c]
[a b c]
[a b c]
[x b c]

如您所见,使用 assing1() 时,local 切片不会因修改传递的切片而受到影响。

使用 assing2() 时,local 切片的元素反映原始切片中所做的更改。

请阅读相关博客文章:

The Go Blog: Go Slices: usage and internals

The Go Blog: Arrays, slices (and strings): The mechanics of 'append'

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>