Last active
January 22, 2018 17:02
Star
You must be signed in to star a gist
github.com/pciet/unordered with https://github.com/golang/go/issues/15292#issuecomment-359347858
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// wins for container types is compile-time type check without a wrapper type | |
// but now a Value() method is required on the contained item interface instead of using a type assertion | |
type Comparable interface { | |
Equal(Ť) bool | |
Value() Ť | |
} | |
type EqualSet []Comparable | |
func (an EqualSet) Remove(the Comparable) EqualSet { | |
out := make(EqualSet, 0, len(an)) | |
found := false | |
for _, item := range an { | |
if found==false && item.Equal(the) { | |
found = true | |
continue | |
} | |
out = out.Add(item) | |
} | |
return out | |
} | |
// no need for "return CoordinateSet(EqualSet(inputcoordinateset).Remove(coordinate))" method | |
type Coordinate struct { | |
X int | |
Y int | |
} | |
func (the Coordinate) Equal(to Coordinate) bool { | |
if the == to { | |
return true | |
} | |
return false | |
} | |
func (the Coordinate) Value() Coordinate { | |
return the | |
} | |
func main() { | |
set := make(EqualSet, 8) | |
for i := 0; i < 8; i++ { | |
set[i] = Coordinate{i, i} | |
} | |
totalX := 0 | |
for _, x := range set { | |
// before this would be a type assertion instead of a required Value() method on the interface | |
totalX += x.Value().X | |
} | |
fmt.Println(totalX) | |
fmt.Println(set.Remove(Coordinate{2, 2})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment