dpbe81245
2017-11-25 13:40
浏览 81
已采纳

请说明golang类型是否按值传递

I'm trying to make a very simple program that modifies arrays, but ran across some interesting behavior if I converted them to types. https://play.golang.org/p/KC7mqmHuLw It appears that if I have an array go passes by reference, but if I have a type then go passes by value. Is this correct?

I have two variables b and c, both are arrays of 3 integers, but c is of type cT, in every other respect they should be identical. I can assign values as b[0]=-1 and c[0]=-1, but if I pass those arrays as parameters to a function they act very differently.

The output of the program is:

before b: [1 2 3]

before c: [1 2 3]

*after b: [-1 2 0]

*after c: [-1 2 3]

*what? c: [-1 2 0]

My initial assumption is that the lines "after b" and "after c" should have been the same. Am I doing something incorrectly or am I correct about types passing to functions by value (ie. creating copy of the variable before passing to the function)?

package main

import "fmt"

type cT [3]int

func main() {
    b := []int{1, 2, 3}
    c := cT{1, 2, 3}

    fmt.Println("before b:", b)
    fmt.Println("before c:", c)

    b[0] = -1
    c[0] = -1
    mangleB(b) // ignore return value
    mangleC(c) // ignore return value

    fmt.Println("*after b:", b)
    fmt.Println("*after c:", c)

    c = mangleC(c)    
    fmt.Println("*what? c:", c)    
}

func mangleB(row []int) []int {
    row[2] = 0
    return row
}

func mangleC(row cT) cT{
    row[2] = 0
    return row
}

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

我正在尝试编写一个非常简单的程序来修改数组,但是如果我将其转换,则会遇到一些有趣的行为 类型。 https://play.golang.org/p/KC7mqmHuLw 看来,如果我有一个 数组按引用传递,但是如果我有一个类型,则按值传递。 这是正确的吗?

我有两个变量b和c,它们都是3个整数的数组,但是c的类型是cT,在所有其他方面它们应该是相同的。 我可以将值分配为 b [0] =-1 c [0] =-1 ,但是如果我将这些数组作为参数传递给函数,则它们的行为会大不相同 。

程序的输出为:

b之前:[1 2 3] \ c之前的n

:[1 2 3]

* b之后的c:[-1 2 0]

* c之后的c:[- 1 2 3]

*什么? c:[-1 2 0]

我最初的假设是,“ b之后”和“ c之后”行应该相同。 我是做错了事还是对通过值传递给函数的类型是正确的(即在传递给函数之前创建变量的副本)?

  package main 
 \  nimport“ fmt” 
 
type cT [3] int 
 
func main(){
b:= [] int {1,2,3} 
c:= cT {1,2,3} 
 \  n fmt.Println(“在b:”之前,b)
 fmt.Println(“在c:”之前,c)
 
b [0] = -1 
c [0] = -1 
 mangleB(b  )//忽略返回值
 mangleC(c)//忽略返回值
 
 fmt.Println(“ *之后b:”,b)
 fmt.Println(“ *之后c:”,c)\  n 
c = mangleC(c)
 fmt.Println(“ * what?c:”,c)
} 
 
func mangleB(row [] int)[] int {
 row [2] = 0  
返回行
} 
 
func mangleC(row cT)cT {
 row [2] = 0 
返回行
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题