Mic*_*ser 17 return-value go multiple-return-values
在Go中,以下工作(注意一个地图的使用有一个返回,另一个有两个返回)
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)
}
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何用自己的功能做同样的事情.是否有可能与可选的返回类似的行为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)
}
Run Code Online (Sandbox Code Playgroud)
不会编译(由于错误multiple-value Hello() in single-value context
)...有没有办法使这个语法适用于该函数Hello()
?
icz*_*cza 25
map
是不同的,因为它是一个内置类型而不是一个函数.访问a元素的两种形式map
由Go语言规范:索引表达式指定.
有了功能,你无法做到这一点.如果一个函数有2个返回值,你必须"期望"它们两个或根本没有.
但是,您可以将任何返回值分配给Blank标识符:
s, b := Hello() // Storing both of the return values
s2, _ := Hello() // Storing only the first
_, b3 := Hello() // Storing only the second
Run Code Online (Sandbox Code Playgroud)
您也可以选择不存储任何返回值:
Hello() // Just executing it, but storing none of the return values
Run Code Online (Sandbox Code Playgroud)
注意:您也可以将两个返回值分配给空白标识符,尽管它没有用(除了验证它有2个返回值):
_, _ = Hello() // Storing none of the return values; note the = instead of :=
Run Code Online (Sandbox Code Playgroud)
您也可以在Go Playground上试试这些.
辅助功能
如果您多次使用它并且不想使用空白标识符,请创建一个放弃第二个返回值的辅助函数:
func Hello2() string {
s, _ := Hello()
return s
}
Run Code Online (Sandbox Code Playgroud)
现在你可以这样做:
value := Hello2()
fmt.Println(value)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5432 次 |
最近记录: |