3

Take the following piece of code:

type A struct { … }
func (a *A) Attr() int { … }

type B struct { … }
func (b *B) Attr() int { … }

type I interface{
  Attr() int
}

func (m that implements I) Process() int {
  do something with m.Attr()
}

func main() {
  a := A{}
  a.Process()
  b := B{}
  b.Process()
}

Methods cannot be defined on interfaces so m cannot be of type I. I tried using anonymous fields on A and B but Attr is specific to the associated structs so it can't be implemented on an anonymous field.

I want to avoid copy/pasting the Process() method on A and B since it is exactly the same. I could simply define

func Process(m I) int { … }

instead but it's not very elegant.

How would you go about doing this the go way?

5
  • 3
    why Process(m I) int is not elegant ? Commented Dec 12, 2014 at 21:34
  • 4
    A function that takes an interface is the idiomatic way to do it. Commented Dec 12, 2014 at 21:35
  • 1
    Everything doesn't have to be a method like in some other OOP languages (e.g. Ruby). Commented Dec 12, 2014 at 21:36
  • 1
    Yes, I think I have to get rid of my OO reflexes ;-) Commented Dec 12, 2014 at 21:37
  • 1
    I agree that func Process(m I) int { … } seems to be the way to go. play.golang.org/p/t59t5KHlw6 . Commented Dec 12, 2014 at 23:38

1 Answer 1

2

This is not currently possible in Go. While you can introduce common methods to a number of types via embedding another type within a struct, those methods have no knowledge of the type they have been embedded in.

The usual Go idiom for this pattern is to use a function. As an example, sort package from the standard library. It defines an interface consisting of the methods needed to implement a sort algorithm on a container (Len, Less, and Swap). However, the actual sort algorithm is exposed as a function that takes an argument implementing the interface.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.