我是golang的新手,如果这个问题太天真,请道歉。环顾四周,但找不到我的基本问题的答案。
假设我有一个具体的结构和方法,如下所示。
type MyData struct{
field1 string
field2 int
}
func(a MyData) OperatorOnString() string{
return a.field1.(string)
}
func(a MyData) OperatorOnInt() int{
return a.field2.(int)
}
我的问题是,我可以键入 cast 并返回而不是执行断言吗?从我目前了解到的情况来看,断言用于接口(interface)类型的数据。但在这种情况下,我有具体的类型。我应该仍然使用断言还是可以执行 return int(a.field2)
之类的操作。我知道这个例子很简单,但我感到困惑的是何时在两种转换类型之间使用。还是这里涉及到一些 golang 惯用语?
谢谢
最佳答案
首先,type assertion只能在接口(interface)上使用:
For an expression
x
of interface type and a typeT
, the primary expression
x.(T)
asserts that
x
is not nil and that the value stored inx
is of typeT
. The notationx.(T)
is called a type assertion.
但您将其应用于非接口(interface)类型字段(int
和 string
)。这使得编译器 unhappy .
其次,如果你想从方法/函数返回类型 T
,返回一个 T
类型的表达式总是足够的,你的字段已经恰好是.正确的代码很容易:
package main
import "fmt"
type MyData struct {
field1 string
field2 int
}
func (a MyData) OperatorOnString() string {
return a.field1
}
func (a MyData) OperatorOnInt() int {
return a.field2
}
func main() {
a := MyData{"foo", 42}
fmt.Println(a.OperatorOnString(), a.OperatorOnInt())
}
输出:
foo 42
关于casting - 具体结构上的类型转换与类型断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442053/