英文:
usage of interface{} on a struct to check if it satisfies an interface in golang
问题
给定以下代码:
package main
import (
"fmt"
)
type work interface {
filter() bool
}
type organ struct {
name string
}
func (s *organ) filter() bool {
return true
}
func main() {
kidney := &organ{
name: "kidney",
}
_, ok := interface{}(kidney).(work)
fmt.Println(ok)
}
我没有完全理解以下部分:
_, ok := interface{}(kidney).(work)
在我看来,它将结构体转换为interface{}
类型,这一点我理解,但为什么需要将其转换为interface{}
类型来检查它是否满足另一个接口呢?更具体地说,为什么以下代码会失败?
ok := kidney.(work)
并显示错误信息:
invalid type assertion: kidney.(work) (non-interface type *organ on left)
请注意,这段代码中的kidney
是一个指针类型。
英文:
Given the following code:
package main
import (
"fmt"
)
type work interface {
filter() bool
}
type organ struct {
name string
}
func (s *organ) filter () bool {
return true;
}
func main() {
kidney := &organ {
name : "kidney",
}
_, ok := interface{}(kidney).(work)
fmt.Println(ok);
}
I did not fully get the following part:
_, ok := interface{}(kidney).(work)
It seems to me, it is converting struct to the interface{}
type, which I understand, but why is it required to convert to an interface{}
type to check if it satisfies another interface. More specifically, why the following code fails?
ok := kidney.(work)
with error
invalid type assertion: kidney.(work) (non-interface type *organ on left)
答案1
得分: 7
如果你总是知道具体的类型(例如kidney
),那么你就不需要类型断言;只需将其传递给你的work
变量并继续进行--编译器将保证kidney
满足work
接口,否则你的程序将无法编译。
首先将具体类型转换为interface{}
的原因是类型断言(即动态类型检查)只在动态类型(即接口)之间有意义。在编译时,对编译器可以保证的事物进行运行时类型检查是没有意义的。希望这样说得清楚了。
英文:
TL;DR If you always know the concrete type (e.g., kidney
), then you don't need a type assertion; just pass it into your work
variable and carry on--the compiler will guarantee that kidney
satisfies the work
interface, otherwise your program won't compile.
The reason you must first convert the concrete type into an interface{}
is because type assertions (i.e., dynamic type checks) only make sense between dynamic types (i.e., interfaces). It doesn't make sense to do a runtime type check on a thing the compiler can guarantee at compile time. Hopefully this makes sense?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论