【问题标题】:Can someone explain this behaviour to me?有人可以向我解释这种行为吗?
【发布时间】:2019-10-23 10:10:57
【问题描述】:

我只是在 golang 中尝试了一些简单的东西并得到了这种行为

谁能给我解释一下为什么?感觉自己理解错了……

package main

import (
    "fmt"
)

func main() {
    s := []int{1, 2, 3}
    fmt.Println(s)
    fmt.Println("----")
    a := s[0:2]
    fmt.Println(s)
    fmt.Println(a)
    a = append(a, 5)
    fmt.Println("----")
    fmt.Println(s)
    fmt.Println(a)
    a = append(a, 6)
    fmt.Println("----")
    fmt.Println(s)
    fmt.Println(a)
}

Go Playground

回复:

[1 2 3]
----
[1 2 3]
[1 2]
----
[1 2 5]
[1 2 5]
----
[1 2 5]
[1 2 5 6]

我期待:

[1 2 3]
----
[1 2 3]
[1 2]
----
[1 2 3]
[1 2 5]
----
[1 2 3]
[1 2 5 6]

提前致谢,:)

【问题讨论】:

标签: go slice


【解决方案1】:

您使用切片。 Slice 是一个包含三个元素的结构,其中一个是指向包含数据的数组的指针(第二个 - 容量,第三个 - 长度)。

s -> array | 1 | 2 | 3 | 

下一个

a := s[0:2]

现在你有两个切片,但它们都指向同一个数组并且切片共享它们的数据。

s -> array | 1 | 2 | 3 | <- a

下一步:

a = append(a, 5)

在这里,您已将元素添加到第二个切片,但此切片与第一个切片共享相同的数组,因此您重写了第一个切片(和数组)的最后一个元素。

s -> array | 1 | 2 | 5 | <- a

下一个:

a = append(a, 6)

在这里,您已将另一个元素添加到第二个切片。但是用于该切片的数组不能包含更多元素,因此重新创建了第二个切片的数组。 Go 创建了新数组,将第一个数组中的所有元素复制到它,并将这个新数组用于第二个切片。第一个切片仍然使用自己的数组。

s -> array | 1 | 2 | 5 | 
a -> array | 1 | 2 | 5 | 6 |

【讨论】:

  • 感谢您的快速回答。现在我看到它们是指针:)。 As for the a = append(a,6) 我明白你在说什么,但测试似乎第一个附加断开了指针之间的链接;所以'a'只指向第一个追加之前的第一个数组,然后没有连接,对吗?
  • "现在我看到它们是指针" --- 虽然切片不是指针。
  • @zerkms "Now I see they are pointers" - 你在哪里找到的?我没有说切片是指针。我说过:Slice is a structure with three element, one of them is a pointer to array with data
  • @demas 它来自我的评论上方的 OP 评论。 (他们现在已经进行了大量修改)
  • @zerkms,哦……对不起。我现在看到了。当然 slice 不是指针,但它们包含指向数据的指针作为其结构的一部分。
猜你喜欢
  • 2016-09-18
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
  • 2021-12-11
  • 2020-02-23
  • 2019-12-06
相关资源
最近更新 更多