I'm working on a simple linked list implementation in golang for learning purposes. The definition of an element is below:
type Element struct {
next, prev *Element
Value interface{}
}
As you can see, the Value can be anything that satisfies the empty interface. Now, as a new feature, I would like to make it so that when you insert a new element into the list, it inserts it in a sorted manner - each element will be <= the next.
In order to do this, I wrote the following method:
func (l *LinkedList) Add(val interface{}) *Element {
this := &l.Root
e := Element{Value: val}
for {
if this.next.Value != nil && this.next.Value < val { // <-comparison here
this = this.next
} else {
return l.insert(&e, this)
}
}
}
The compiler complains operator < not defined on interface
which is fair. So I understand that in my Element typedef, I should restrict Value to types that can be compared using the <
operator. I learned this while researching this problem that golang does not support operator overloading - I am not trying to do that. Instead, I am just trying to make sure that Element.Value is a type that can be compared using the <
operator. How do I do this?
Update:
It occurs to me that it might not be too difficult to simple define a new type, based on a built-in, that can be compared through some function. so I wrote this mess (as well as a bunch of other ways of trying to do the same thing):
type Comparable interface {
LessThan(j interface{}) bool // tried (j Comparable), (j MyInt), etc
EqualTo(j interface{}) bool // tried (j Comparable), (j MyInt), etc
}
type MyInt int
func (i MyInt) LessThan(j MyInt) bool {
return i < j
}
func (i MyInt) EqualTo(j MyInt) bool {
return i == j
}
type Element struct {
next, prev *Element
Value Comparable
}
What I would really like is to define an interface, which, if implemented for a type, provides functions LessThan
and EqualTo
that operate on two instances of that type and provides a bool - something like LessThan(i, j WhatEvers) bool
which can be used in place of <
. I realize below it's implemented as an instance method - I've tried both ways but no success. With the above, I would use it something like: this.next.Value.LessThan(val)
in the Add function. I get either:
linkedlist.MyInt does not implement linkedlist.Comparable (wrong type for EqualTo method)
have EqualTo(linkedlist.MyInt) bool
want EqualTo(interface {}) bool
or
linkedlist.MyInt does not implement linkedlist.Comparable (wrong type for EqualTo method)
have EqualTo(linkedlist.MyInt) bool
want EqualTo(linkedlist.Comparable) bool
Is this possible to use an interface to require that a certain function must exist that operates on two instances of a custom type, or is it only for Methods?