Hi Alex,
Thanks for the response. Apologies for the confusion. The Generic method
indeed uses struct fields from P1data/P2data struct(they are all same
structs). Can I still achieve this? From the below. GenericMethod should
read name field from structs.
//package p1
type P1data struct {
name string
}
//package p2
type P1data struct {
name string
}
-Thanks
On Wednesday, April 25, 2018 at 10:16:24 AM UTC+5:30, [email protected]
wrote:
>
> If GenericMethod is truly the same, as in not even using the struct fields
> from P1data/P2data then there is a way. You just need to create a new
> struct type in package main that implements GenericMethod and then in
> packages p1 and p2 you embed the struct and thus expose the method.
>
> package main
>
>
> import (
> "fmt"
> )
>
>
> type I interface {
> F1()
> GenericMethod()
> }
>
>
> type Generic struct{}
>
>
> func (*Generic) GenericMethod() {
> fmt.Printf("Hello World")
> }
>
> //package p1
> type P1data struct {
> Generic
> }
>
>
> func (x *P1data) F1() {}
>
>
> func main() {
> i := I(&P1data{})
> i.GenericMethod()
> }
>
>
>
>
>
>
> On Wednesday, 25 April 2018 12:01:36 UTC+8, [email protected] wrote:
>>
>> Hello all,
>>
>> I am golang beginner. And I have a problem with interfaces.
>> Here is the problem where I have one main package with has an Interface
>> I. and multiple sub packages each implementing interface I. So I have a
>> method which is exactly the same for all sub packages. Is there a way I can
>> implement this method for I.
>>
>> package main
>>
>> type I interface {
>> F1()
>> GenericMethod() // Is there a way I can implement it on I
>> since its the same in all packages?
>> }
>>
>> package p1
>>
>> type P1data struct {}
>>
>> (x *P1data) F1()
>> (x *P1data) GenericMethod()
>>
>>
>> package p2
>>
>> type P2data struct {}
>>
>> (x *P2data) F1()
>> (x *P2data) GenericMethod()
>>
>>
>> under the main package.
>> for each data in sub packages do data.F1 and data.GenericMethod().
>>
>>
>> Now I don't want to implement GenericMethod for all packages. Since its
>> the same.So can I implement GenericMethod on I (I know this is not
>> possible). But how can do something like this?
>>
>> -Thanks
>>
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.