HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMajor

Meaning of a struct with embedded anonymous interface?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
embeddedwithstructmeaninginterfaceanonymous

Problem

sort package:

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

...

type reverse struct {
    Interface
}


What is the meaning of anonymous interface Interface in struct reverse?

Solution

In this way reverse implements the sort.Interface and we can override a specific method
without having to define all the others

type reverse struct {
        // This embedded Interface permits Reverse to use the methods of
        // another Interface implementation.
        Interface
}


Notice how here it swaps (j,i) instead of (i,j) and also this is the only method declared for the struct reverse even if reverse implement sort.Interface

// Less returns the opposite of the embedded implementation's Less method.
func (r reverse) Less(i, j int) bool {
        return r.Interface.Less(j, i)
}


Whatever struct is passed inside this method we convert it to a new reverse struct.

// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface {
        return &reverse{data}
}


The real value comes if you think what would you have to do if this approach was not possible.

  • Add another Reverse method to the sort.Interface ?



  • Create another ReverseInterface ?



  • ... ?



Any of this change would require many many more lines of code across thousands of packages that want to use the standard reverse functionality.

Code Snippets

type reverse struct {
        // This embedded Interface permits Reverse to use the methods of
        // another Interface implementation.
        Interface
}
// Less returns the opposite of the embedded implementation's Less method.
func (r reverse) Less(i, j int) bool {
        return r.Interface.Less(j, i)
}
// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface {
        return &reverse{data}
}

Context

Stack Overflow Q#24537443, score: 96

Revisions (0)

No revisions yet.