Skip to content

Instantly share code, notes, and snippets.

@pciet
Last active January 22, 2018 17:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pciet/36a9dcbe99f6fb71f5fc2d3c455971e5 to your computer and use it in GitHub Desktop.
// 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