duaner5714 2017-06-23 08:01
浏览 162
已采纳

func foo(arr [] int)int和func foo(arr [num] int)int有什么区别?

What's the difference between func foo(arr []int) int and func foo(arr [*num*]int) int?

Here are two examples:

func foo1(arr [2]int) int {
    arr[0] = 1
    return 0
}

func foo2(arr []int) int {
    arr[0] = 1
    return 0
}

func main() {
    var arr1 = [2]int{3, 4}
    var arr2 = []int{3, 4}
    foo1(arr1)
    println(arr1[0])      // result is 3, so arr in foo1(arr) is a copy
    foo2(arr2)
    println(arr2[0])      // result is 1, so arr in foo2(arr) is not a copy, it is a reference
}

I also found if I use foo1(arr2) or foo2(arr1), the compiler will report an error like "cannot use arr2 (type []int) as type [2]int in argument to foo1" and "cannot use arr1 (type [2]int) as type []int in argument to foo2".

So who can help to explain what's the difference between them or give me some link to study? Thank you in advance.

  • 写回答

3条回答 默认 最新

  • doupao1530 2017-06-23 08:13
    关注

    [2]int is an array, []int is a slice.

    Arrays and slices are completely different types: you can't pass an array where a slice is required, and you can't pass a slice where an array is expected. Since the length is part of the array type, you can't even use array values where the length differs, e.g. you can't use an array value of type [3]int for something that expects [2]int.

    Everything in Go is passed by value. Slices too. But a slice value is a header, describing a contiguous section of a backing array, and a slice value only contains a pointer to the array where the elements are actually stored. The slice value does not include its elements (unlike arrays). When you pass a slice, only the slice header is copied (pointing to the same backing array), and so modifying its elements modifies elements in the same backing array, so the caller will observe the changes. Read more about this here: Are golang slices pass by value? To see what's in a slice header: reflect.SliceHeader.

    Unlike slices, arrays are not headers. An array value means all its elements, so when you pass an array value, all its elements are copied, and inside the function it is passed to you can only modify this copy array; the caller won't observe the changes made to the array (e.g. changing its elements).

    Note that however it is very easy to obtain a slice value from an array, you may simply use slicing:

    var a [2]int = [2]int{1, 2}
    var s []int = a[:]
    fmt.Println(s) // Prints [1 2]
    

    Recommended blog post: Go Slices: usage and internals

    More insight into arrays vs slices: Why have arrays in Go?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型