I am trying to implement a sorted linked list in golang. And it’s not easy for me to come up with a general way to make the linked list work with any type that can be compared to itself. Starting with its sorted list, I want the "go compiler" to provide a comparison of the values inserted in the linked list.
For instance,
import "linkedlist"
type Person struct {
name string
}
func main() {
l := linkedlist.New()
p := Person{"Jay"}
l.insert(p)
}
In the above example, how to make a compiler, make sure that the value of 'p', which is of type "Person", can be compared with another value, which is also of type "Person". I want the compiler to catch an error in situations where the inserted value is not a suitable value.
I can do something like this
import "linkedlist"
type Element interface {
func IsGreater(v Element{}) bool
}
type Person struct {
name string
age int
}
func (p *Person) IsGreater(p1 interface{}) bool {
if ok, v := p1.(Person); ok && p.age > v.age {
return true
}
return false
}
, "" , IsGreater, , .
...
sort.Sort , . , , , , Len, Less Swap.
, , . , , 2 .. , .