Last active
January 22, 2018 17:02
-
-
Save pciet/36a9dcbe99f6fb71f5fc2d3c455971e5 to your computer and use it in GitHub Desktop.
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