Saturday, 7 October 2017

go - Golang: Type aliasing Structures That Meet a Interface Requirement



See code below:



I have an odd behavior that I can't understand in Golang. If I want to create a type alias of a structure and that structure meets the requirements of a interface type, then the type alias won't meet the requirements of that interface type. I have no idea why this is happening. Any thoughts?



package main

import (
"fmt"

)

type MyInt struct {
value int
}

func (m MyInt) DoubleIt() int {
return m.value * 2
}


type MyInter interface {
DoubleIt() int
}

type MyIntContainer struct {
d MyInter
}

type MC MyIntContainer
type MI MyInt


func main() {
e1 := MyIntContainer{MyInt{12}} //This is OK
fmt.Printf("%d\n", e1.d.DoubleIt())
e2 := MC{MI{12}} //this fails with error - line 29
fmt.Printf("%d\n", e2.d.DoubleIt())
}


The error message:

Line 29: cannot use MI literal (type MI) as type MyInter in field value:
MI does not implement MyInter (missing DoubleIt method)


Answer



In your code MI is a new type which doesn't carry over the methods from the original type. The DoubleIt method really isn't available:



e2 := MI{12}
fmt.Printf("%d\n", e2.DoubleIt())




e2.DoubleIt undefined (type MI has no field or method DoubleIt)



An alternative if you want to carry over the methods would be to embed MyInt:



type MI struct {
MyInt
}



Then you can say:



e2 := MI{MyInt{12}}
fmt.Printf("%d\n", e2.DoubleIt())





From the spec:





A type may have a method set associated with it. The method set of any
other type T consists of all methods declared with receiver type T. Further rules apply to structs containing anonymous fields, as
described in the section on struct types. Any other type has an empty
method set
.



No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...