usage of interface{} on a struct to check if it satisfies an interface in golang

huangapple go评论79阅读模式
英文:

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?

huangapple
  • 本文由 发表于 2016年11月3日 23:25:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/40405407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定