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

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.

图片转代码服务由CSDN问答提供 功能建议

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

下面是两个示例:

  func foo1(  arr [2] int)int {
 arr [0] = 1 
返回0 
} 
 
func foo2(arr [] int)int {
 arr [0] = 1 
返回0 
  } 
 
func main(){
 var arr1 = [2] int {3,4} 
 var arr2 = [] int {3,4} 
 foo1(arr1)
 println(arr1 [0]  )//结果为3,因此foo1(arr)中的arr为副本
 foo2(arr2)
 println(arr2 [0])//结果为1,因此foo2(arr)中的arr不是副本, 它是参考
} 
   
 
 

我还发现我是否使用 foo1(arr2) foo2(arr1)< / code>,编译器将报告错误,例如“不能将arr2(类型[] int)用作foo1的参数中的类型[2] int” “不能使用arr1(类型[ 2] int)作为foo2参数中的[] int类型。

那么谁能帮助解释它们之间的区别或给我一些链接, 读书吗 预先谢谢您。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题