Idiomatic way to do conversion/type assertion on multiple return values in Go

后端 未结 4 610
花落未央
花落未央 2021-01-30 08:12

What is the idiomatic way to cast multiple return values in Go?

Can you do it in a single line, or do you need to use temporary variables such as I\'ve done in my exampl

4条回答
  •  面向向阳花
    2021-01-30 08:36

    func silly() (interface{}, error) {
        return "silly", nil
    }
    
    v, err := silly()
    if err != nil {
        // handle error
    }
    
    s, ok := v.(string)
    if !ok {
        // the assertion failed.
    }
    

    but more likely what you actually want is to use a type switch, like-a-this:

    switch t := v.(type) {
    case string:
        // t is a string
    case int :
        // t is an int
    default:
        // t is some other type that we didn't name.
    }
    

    Go is really more about correctness than it is about terseness.

提交回复
热议问题