How to check if struct implements given interface by self?


(shihaonan369) #1

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


(Johan Dahl) #2

Hi. What are you trying to achieve?


( Kvaz1r) #3

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.


(shihaonan369) #4

@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.


(Johan Dahl) #5

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