在普通函数上返回像 Golang 中的“ok"这样的地图 [英] Return map like 'ok' in Golang on normal functions
问题描述
在 Go 中,如下工作(注意使用 map 有一个返回,另一个有两个返回)
In Go, the following works (note one use of the map has one return, the other has two returns)
package main
import "fmt"
var someMap = map[string]string { "some key": "hello" }
func main() {
if value, ok := someMap["some key"]; ok {
fmt.Println(value)
}
value := someMap["some key"]
fmt.Println(value)
}
然而,我不知道如何用我自己的函数来做同样的事情.是否有可能通过像 map
这样的可选返回来实现类似的行为?
However, I have no idea how to do this same thing with my own function. Is it possible to have similar behavior with an optional return like map
?
例如:
package main
import "fmt"
func Hello() (string, bool) {
return "hello", true
}
func main() {
if value, ok := Hello(); ok {
fmt.Println(value)
}
value := Hello()
fmt.Println(value)
}
无法编译(由于错误multiple-value Hello() in single-value context
)......有没有办法使这个语法适用于函数Hello()
?
Wont compile (due to the error multiple-value Hello() in single-value context
) ... is there a way to make this syntax work for the function Hello()
?
推荐答案
map
是不同的,因为它是一个内置的 type 而不是一个函数.访问 map
元素的 2 种形式由 Go 语言规范指定: 索引表达式并由编译器支持.
map
is different because it is a built-in type and not a function. The 2 forms of accessing an element of a map
is specified by the Go Language Specification: Index Expressions and backed by the compiler.
对于函数,您无法做到这一点.如果一个函数有 2 个返回值,你必须期望"两者都有或根本没有.
With functions you can't do this. If a function has 2 return values, you have to "expect" both of them or none at all.
但是,您可以将任何返回值分配给空白标识符:
However you are allowed to assign any of the return values to the Blank identifier:
s, b := Hello() // Storing both of the return values
s2, _ := Hello() // Storing only the first
_, b3 := Hello() // Storing only the second
您也可以选择不存储任何返回值:
You can also choose not to store any of the return values:
Hello() // Just executing it, but storing none of the return values
注意:您也可以将两个返回值都分配给空白标识符,尽管它没有任何用处(除了验证它恰好有 2 个返回值):
Note: you could also assign both of the return values to the blank identifier, although it has no use (other than validating that it has exactly 2 return values):
_, _ = Hello() // Storing none of the return values; note the = instead of :=
您也可以在 Go Playground 上尝试这些.
You can also try these on the Go Playground.
辅助函数
如果您多次使用它并且不想使用空白标识符,请创建一个丢弃第二个返回值的辅助函数:
If you use it many times and you don't want to use the blank identifier, create a helper function which discards the 2nd return value:
func Hello2() string {
s, _ := Hello()
return s
}
现在你可以:
value := Hello2()
fmt.Println(value)
这篇关于在普通函数上返回像 Golang 中的“ok"这样的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!