Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement a Golang interface method that takes itself as a paremeter?

I am trying to create a generic Addable type in Golang. Here’s a toy example of what I’m trying to do:

package main

type Addable interface {
    // Note that `Add` takes an `Addable` as argument.
    Add(other Addable) Addable
}

type Point2d struct {
    x int
    y int
}

// Note that I cannot pass `other` as `Addable` because I need
// access to the fields x and y to implement the method.
func (p *Point2d) Add(other *Point2d) Addable {
    return &Point2d{p.x + other.x, p.y + other.y}
}

func SumAddables(a, b, c Addable) Addable {
    return a.Add(b).Add(c)
}

The above code does not compile. I get the following error:

./prog.go:16:9: cannot use &Point2d{…} (value of type *Point2d) as Addable value in return statement: *Point2d does not implement Addable (wrong type for method Add)
        have Add(*Point2d) Addable
        want Add(Addable) Addable

Link to Go playground: https://go.dev/play/p/eUmqZTZO1ow

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any idea how to implement such an interface in Golang?

>Solution :

I need to pass other as *Point2d to implement the Add() method because I need access to the Point2d fields.

That would also be true of the implementation of Add for any other type. If you want a generic Add(Addable) Addable you’ll need to do a type assertion inside Add to handle the types you can add together.

func (p *Point2d) Add(other Addable) Addable {
    switch v := other.(type) {
    case *Point2d:
        return &Point2d{p.x + v.x, p.y + v.y}
    default:
        panic(fmt.Errorf("Unhandled type %T", other))
    }
}

(Full implementation at https://go.dev/play/p/KAFIhgjJ5Xs)

For what it’s worth, this isn’t really Go Generics programming; it’s simply satisfying the interface.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading