doudou348131346 2012-07-31 09:29
浏览 64
已采纳

数组和切片数据类型

I found myself confused with the array and slice data types.

From Go docs, arrays are described as follows:

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.

Functions:

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.

Why does sort.Ints(arrayValue) modify the passed variable when I declared it as an array, not as a slice?

Code

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

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

Output

[1 5 2 3 7]
[1 2 3 5 7]
  • 写回答

5条回答 默认 最新

  • douzhang6496 2012-07-31 09:39
    关注

    See "Slices: usage and internals"

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

    That is a slice, not an array.

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

    That explains why the sort function will modify the content of what is referenced by the slice.

    As commented below by Kirk, sort.Ints will give you an error if you passed it an array instead of a slice.

    func Ints(a []int)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog