doumu5934 2016-03-27 06:59
浏览 27
已采纳

为什么map和type断言可以返回1或2值

map we can do such:

value, present := m["key"]

or

value := m["key"]

and type assertion

var i interface{} = "hello"

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

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

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

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

when invoke the func:

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

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

Thanks in advance. (am I clear? poor English sorry.

  • 写回答

2条回答 默认 最新

  • du131642 2016-03-27 12:10
    关注

    The Go Programming Language Specification

    Function types

    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 .
    

    Blank identifier

    The blank identifier is represented by the underscore character _.

    Assignments

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

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

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?