最佳答案
在 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)