在 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
当涉及到接口时,它会被调用吗?
i := interface.(int)