在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)