go - 请解释 golang 类型是否按值传递

标签 go parameter-passing pass-by-reference pass-by-value pass-by-pointer

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

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

程序的输出是:

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]

我最初的假设是“在 b 之后”和“在 c 之后”这行应该是相同的。我是不是做错了什么,或者我是否纠正了按值传递给函数的类型(即在传递给函数之前创建变量的副本)?

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
}

最佳答案

The Go Programming Language Specification

Array types

An array is a numbered sequence of elements of a single type, called the element type.

Slice types

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

Calls

In a function call, the function value and arguments are evaluated in the usual order. After they are evaluated, the parameters of the call are passed by value to the function and the called function begins execution. The return parameters of the function are passed by value back to the calling function when the function returns.


type cT [3]int

b := []int{1, 2, 3}
c := cT{1, 2, 3}

I have two variables, b and c, both are arrays of 3 integers


不,你不知道!

bint slice ,长度为 (len(b)) 3,容量为 (cap(b)) 3、c是一个array of (len(c)) 3 int

在 Go 中,所有参数都是按值传递的。 b 作为 slice 描述符传递,c 作为数组传递。 slice 描述符是一个结构,具有 slice 长度和容量,以及指向底层数组的指针。

关于go - 请解释 golang 类型是否按值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486606/

相关文章:

go - 如何防止格式错误的上传?

bash - 在 bash 中传递空变量

parameter-passing - 将参数传递给函数而不在 JULIA-LANG 中复制它们

python - 将参数传递给 Zope 浏览器页面

c - 为什么需要在 C 中用 * 定义对指针的引用?

python - 如何通过引用传递变量?

javascript - 内部网络上的 Websockets 地址需要静态 ip?

bash - 在 Jenkins 中使用脚本在不同阶段运行

c++ - 在 C++ 中通过引用传递时参数的默认值

python - 如何使用 Go 和 Python 处理 YAML 中的十六进制值?