为什么map和type断言可以返回1或2个值? [英] Why map and type assertion can return 1 or 2 values?

查看:228
本文介绍了为什么map和type断言可以返回1或2个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要定义地图,我们可以做这样的事情:

To define a map, we can do such a thing:

value, present := m["key"]

或:

value := m["key"]

并使用类型断言,我们可以做到:

and with type assertion, we can do:

var i interface{} = "hello"

s := i.(string)
fmt.Println(s)

s, ok := i.(string)
fmt.Println(s, ok)

但是我找不到定义可以返回1个值或2个值的func的方法.

but I can't find a way to define a func that can return 1 value or 2-values.

例如:

func hello() (string, error) {
    return "world", nil
}

当我调用此函数时,我得到:

When I invoke this func I get:

v, ok := hello() // valid
v := hello() // invalid

PS:我知道template.Must之类的东西是如何工作的,但似乎有所不同.我真的很想知道Map和类型断言如何发挥作用,因此可以将其应用于函数.

PS: I know how something like template.Must works, but it seems different. I really want to know how Map and type assertion can do the magic, so I can apply it to functions.

先谢谢了. (我知道吗?我英语不好,很抱歉).

Thanks in advance. (Am I clear? I have poor English sorry).

推荐答案

Go编程语言规范

函数类型

函数类型表示具有相同功能的所有函数的集合 参数和结果类型.

A function type denotes the set of all functions with the same parameter and result types.

FunctionType   = "func" Signature .
Signature      = Parameters [ Result ] .
Result         = Parameters | Type .
Parameters     = "(" [ ParameterList [ "," ] ] ")" .
ParameterList  = ParameterDecl { "," ParameterDecl } .
ParameterDecl  = [ IdentifierList ] [ "..." ] Type .

空白标识符

空白标识符由下划线字符_表示.

The blank identifier is represented by the underscore character _.

任务

空白标识符提供了一种忽略右侧值的方法 在作业中:

The blank identifier provides a way to ignore right-hand side values in an assignment:

x, _ = f()  // evaluate f() but ignore second result value

映射,类型断言和带有range子句的for语句是Go编程语言的特殊功能.普通函数类型的返回值数目不能可变.

Maps, type assertions, and the for statement with a range clause are special features of the Go programming language. You can't have a variable number of return values for an ordinary function type.

您可以忽略带有下划线(_),空白标识符的返回值,也可以使用包装函数.例如,

You can ignore a return value with an underscore (_), the blank identifier, or you can use a wrapper function. For example,

package main

import "fmt"

func two() (int, bool) {
    return 42, true
}

func one() int {
    r, _ := two()
    return r
}

func main() {
    r, ok := two()
    r, _ = two()
    r = one()
    fmt.Println(r, ok)
}

这篇关于为什么map和type断言可以返回1或2个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆