是否可以根据分配给函数的变量数量返回不同数量的值?

问题描述 投票:0回答:1

我有一个函数

foo()
,它返回一个
int
和一个
bool
,布尔值是函数是否正确执行。如果呼叫者只想要
int
,他可以键入
value, _ := foo()
。有没有办法设置它,以便调用者只需键入
value := foo()
并且它会自动只返回 int,就像
range
可以返回索引和值,或者只返回索引?

示例代码:

func foo(num int) (int, bool) {
    if num % 2 == 1 {
        //function fails
        return 0, false
    }

    //function succeeds
    return num + 5, true
}

func main() {
    value1, _ := foo(6) //works

    value2 := foo(6) //assignment mismatch
}
function go return variable-assignment
1个回答
0
投票

Go 编程语言的特殊功能包括映射、类型断言、带有

for
子句的
range
语句和通道接收具有可变数量的返回值。但是对于常规函数类型,返回值的数量不能是可变的。

  • 地图
m := make(map[string]int)

m["one"] = 1

// `val` is for a key with name[key].
val := m["one"] 

// `val` is for a key with name[key]. 
// `ok` indicates if the key was present in the map.
val,ok := m["one"]
  • for
    带有
    range
    从句的语句
arr := []int{1, 2, 3, 4}

// `idx` Value is a copy of the element at that index.
for idx := range arr {
 ...
}

// `idx` is the index and `val` is a copy of the element at that index.
for idx, val := range arr {
 ...
}
  • 类型断言

var i interface{}
i = 1

// `num` are the underlying value and `ok` is a boolean value that reports whether the assertion succeeded or not.
num, ok := i.(int)

// `num`e is the underlying value.
num := i.(int)

  • 频道接收
c := make(chan int, 2)

c <- 12
c <- 21

// `val` indicates the received value from the channel.
val := <-c

// `val` the received value from the channel. `ok` is a boolean which indicates if there are no more values to receive and the channel is closed or not.
val, ok := <-c

© www.soinside.com 2019 - 2024. All rights reserved.