How to check if struct implements given interface by self?

https://play.golang.org/p/A_9CbQ6z_lC
How to check if struct implements given interface by self?

Hi. What are you trying to achieve?

2 Likes

I’m not an expert in reflection, but guess you can use something like this:

	b := B{}
	var p interface{} = &b
	_, isImpl := p.(I)
	_, ok := reflect.ValueOf(p).Elem().FieldByName("A").Interface().(I)
	if isImpl && !ok {
		p.(I).Init()
	}

https://play.golang.org/p/kd41LUIwe0t

But for me it’s seems a bit unusual.

@johandalabacka @GreyShatter
The original description is incorrect, has modified.
I’m trying to implement inheritance like c++, Init same as constructor, if not distinguish, Init of embedded struct will be called many times.

Hi again. Are you doing this as an intellectual exercise or are you thinking about using this in a real program? If it is the later I think you are fighting against go: Usually in go then you want to create a new struct where you have to do more than just create the struct with its zero values you do it something like this:

https://golang.org/doc/effective_go.html#composite_literals

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.