gpt4 book ai didi

arrays - 数组和 slice 数据类型

转载 作者:IT老高 更新时间:2023-10-28 12:58:47 25 4
gpt4 key购买 nike

我发现自己对 arrayslice 数据类型感到困惑。

在 Go 文档中,数组描述如下:

There are major differences between the ways arrays work in Go and C. In Go,

  • Arrays are values. Assigning one array to another copies all the elements.
  • In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.
  • The size of an array is part of its type. The types [10]int and [20]int are distinct.

功能:

As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter. For instance, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to.

为什么 sort.Ints(arrayValue) 在我将传递的变量声明为数组而不是 slice 时会修改它?

代码

var av = []int{1,5,2,3,7}

fmt.Println(av)
sort.Ints(av)
fmt.Println(av)
return

输出

[1 5 2 3 7]
[1 2 3 5 7]

最佳答案

参见“Slices: usage and internals

var av = []int{1,5,2,3,7}

这是一个 slice ,而不是一个数组。

A slice literal is declared just like an array literal, except you leave out the element count.

这就解释了为什么排序函数会修改 slice 所引用内容的内容

正如下面 Kirk 所评论的那样, sort.Ints如果您将数组而不是 slice 传递给它,则会给您一个错误。

func Ints(a []int)

关于arrays - 数组和 slice 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11737053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com