我有一个函数
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
}
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