gpt4 book ai didi

go - 如何理解golang的多返回值

转载 作者:IT王子 更新时间:2023-10-29 01:48:45 24 4
gpt4 key购买 nike

Golang 支持将多个返回值分配给多个左侧变量。例如:

func test() (string, string) {
return "1", "1"
}

a, b := test()

a, _ := test()

并且接收变量和返回值的个数必须匹配:

b = test()   //wrong

但对于某些内置类型,例如[]或<-,支持可变数量的返回值

key, exist := map[key]

key := map[key]

我可以像这样从 channel 读取值

c <- myChan

c, exist <- myChan

我们如何解释这种不一致?这是为核心 go 运行时/语言保留的功能吗?

最佳答案

此行为在 golang specification 中明确指定:

  1. Receive operator

A receive expression used in an assignment or initialization of the special form

x, ok = <-ch
x, ok := <-ch
var x, ok = <-ch
var x, ok T = <-ch

yields an additional untyped boolean result reporting whether the communication succeeded. The value of ok is true if the value received was delivered by a successful send operation to the channel, or false if it is a zero value generated because the channel is closed and empty.

  1. Index expression

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

  1. Assignments

A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left hand side must match the number of values. For instance, if f is a function returning two values,

x, y = f()

assigns the first value to x and the second to y. In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the nth expression on the right is assigned to the nth operand on the left.

因此,如您所见,此行为是由语言设计指定的,您无法自行实现为 Receive operatorIndex expression 指定的行为。

关于go - 如何理解golang的多返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46271620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com