Need help in in implementing a method on an interface

73 views
Skip to first unread message

rickyu...@gmail.com

unread,
Apr 25, 2018, 12:01:36 AM4/25/18
to golang-nuts
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

alex....@gmail.com

unread,
Apr 25, 2018, 12:46:24 AM4/25/18
to golang-nuts
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()
}

rickyu...@gmail.com

unread,
Apr 25, 2018, 12:58:36 AM4/25/18
to golang-nuts
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

alex....@gmail.com

unread,
Apr 25, 2018, 1:01:41 AM4/25/18
to golang-nuts
Then just do 

type Generic struct{
 name
string
}


func
(*Generic) GenericMethod() {
 fmt
.Printf(name)
}

If you want to access name from p1

type Generic struct{
 
Name string
}


func
(g *Generic) GenericMethod() {
 fmt
.Printf(g.Name)
}

//package p1
func
(x *P1data) F1() {
 x
.Generic.Name = "asdf"
}


Reply all
Reply to author
Forward
0 new messages