如何检查结构体或结构体指针是否符合接口
时间:2024-03-26
浏览:194
作者:佚名
在 Go 语言中,判断一个结构体或结构体指针是否实现了给定的接口可以通过反射来实现。反射机制允许在运行时检查类型的详细信息,包括接口实现。具体来说,可以使用 reflect.implements 方法来判断一个类型是否实现了某个接口。
我需要知道该结构或指向该结构的指针是否实现了给定的接口。
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
func main() {
var a A = A{
i: 5,
}
Serialize(a)
Serialize(&a)
}
type Serializable interface {
//Serialize() string
//Deserialize(string)
Serializebyte() []byte
Deserializebyte(b []byte) (bytesRead int)
}
type A struct {
i int
}
func (*A) Serializebyte() []byte {
return []byte{0x00}
}
func (*A) Deserializebyte(b []byte) (bytesRead int) {
return 0
}
func Serialize(objInt interface{}) []byte {
// this doesn't work
switch v := (objInt).(type) {
case Serializable:
fmt.Printf("I'm Serializable\n")
return v.Serializebyte()
}
fmt.Printf("I'm not Serializable\n")
return []byte{0x00}
}
// this other way also dont work
func Serialize2(objInt interface{}) []byte {
// this doesn't work
_, isSerializable := objInt.(Serializable)
if isSerializable{
fmt.Printf("I'm Serializable\n")
return objInt.(Serializable).Serializebyte()
}
fmt.Printf("I'm not Serializable\n")
return []byte{0x00}
}
// Stdout:
// I'm not Serializable
// I'm Serializable
编辑: 您可以运行上面的代码来看看我的意思。
因为 (*a) 实现 serialized 而不是 a,所以上面的断言不通过,但我想知道 (*a) 是否实现 serializes 或 a 实现是的。
为什么我想要这个?因为如果我能做到这一点,程序员就不需要知道 serialized 是如何工作的。如果不是,程序员应该总是需要传递一个指向 serialized 的指针,并在结构指针而不是结构本身中实现 serialized。
解决方案
当用户为您提供 t 时,使用 *t 通常是一个坏主意。对 *t 的所有修改将不会对用户数据生效。
但如果这是你真正想要的,你可以使用反射。
func testfool(a interface{}) bool {
if _, ok := a.(fool); ok {
return true
}
t := reflect.ptrto(reflect.typeof(a))
fooltype := reflect.typeof((*fool)(nil)).elem()
return t.implements(fooltype)
}
演示:https://play.golang.org/p/rqJe5_KAP6e
编辑:如果您需要通过指针接收器使用该方法,您可以使用 reflect.value 而不是 reflect.type。但是,它会生成参数的额外副本。
func testfool(a interface{}) bool {
if _, ok := a.(fool); ok {
return true
}
t := reflect.typeof(a)
v := reflect.new(t)
v.elem().set(reflect.valueof(a))
ptra := v.interface()
if foo, ok := ptra.(fool); ok {
foo.foo()
return true
}
return false
}
使用 refelct.newat 和 ·reflect.value.interfacedata` 编写无副本版本代码是可以破解的。但强烈不推荐这样做:它很可能会破坏你未来的代码并且难以维护;它在底层使用了不安全的包。
func Serialize(objInt interface{}) []byte {
switch v := objInt.(type) {
case Serializable:
return v.Serializebyte()
}
// do stuf on object that do not implement Serializebyte
}
https://tour.golang.org/methods/16
终于介绍完啦!小伙伴们,这篇关于《如何检查结构体或结构体指针是否符合接口》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
