在 Go 中转换多个返回值的惯用方法是什么?
您可以在一行中完成,还是需要使用临时变量,例如我在下面的示例中所做的?
package main import "fmt" func oneRet() interface{} { return "Hello" } func twoRet() (interface{}, error) { return "Hejsan", nil } func main() { // With one return value, you can simply do this str1 := oneRet().(string) fmt.Println("String 1: " + str1) // It is not as easy with two return values //str2, err := twoRet().(string) // Not possible // Do I really have to use a temp variable instead? temp, err := twoRet() str2 := temp.(string) fmt.Println("String 2: " + str2 ) if err != nil { panic("unreachable") } }
顺便问一下,casting说到接口的时候是不是调用了?
casting
i := interface.(int)
你不能在一行中完成。您的临时变量方法是要走的路。
顺便说一句,当涉及到接口时,它是否称为强制转换?
它实际上被称为类型断言。A型铸造转换不同的是:
var a int var b int64 a = 5 b = int64(a)