Quantcast
Channel: MarsHut
Viewing all articles
Browse latest Browse all 6551

Unexpected polymorphism behavior when calling interface in embedded struct method

$
0
0
I'm getting unexpected behavior when calling an interface within a method,
where the method is implemented by an embedded struct.

Here's an example which illustrates the issue:

package main

import "fmt"

type Automobile struct {

type Delorean struct {

FluxCapacitorMatrix []float64

Automobile

type TurboBoostable interface {

Boost() string

func (auto *Automobile) Run() string {

return auto.Boost()

func (auto *Automobile) Boost() string {

return "auto"

func (delorean *Delorean) Boost() string {

return "delorean"

func main() {

delorean := ෩梭{}

boostVal := delorean.Run()

if boostVal == "auto" {

fmt.Println("Test failed: did not call the delorean specific boost() method")

} else if boostVal == "delorean" {

fmt.Println("Test passed: called the delorean specific boost() method")

// if this is uncommented, then it will pass

// func (delorean *Delorean) Run() string {

// return delorean.Boost()

// }

When Delorean does not implement it's own Run() method, and instead lets
the embedded
struct Automobile provide the Run() method, the Automobile.Run() method
seems to
lose the type information that the parameter is actually a *Delorean, and
so it
calls the Automobile's implementation of the TurboBoostable interface
rather than
the Delorean's implementation.

As mentioned in commented code, if I give the Delorean it's own version of
the
Run() method, then things work as expected. However, this is not
desirable, because
there's nothing that the Delorean needs to do differently in its Run()
method than
Automobile's Run() method, and so it will just end up as needless code
duplication.

Is there any changes I can make to make it behave as expected? Or is there
a better
way to model this so that I wouldn't run into this problem?

Viewing all articles
Browse latest Browse all 6551

Trending Articles