title: How to implement a linked list
body: <p>I'm trying to implement a sorted linked list in Go. And I'm having a hard time coming up with a generic way to make the linked list work with any type that can by compared with itself. Since its a sorted list, I want the 'go compiler' to ensure that the values being inserted into the linked list can be compared.</p>
  
  <p>For example,</p>
  
  <pre><code>import "linkedlist"
  
  type Person struct {
    name string
  }
  
  func main() {
    l := linkedlist.New()
    p := Person{"Jay"}
    l.insert(p)
  }
  </code></pre>
  
  <p>In the above example, how do I make the compiler ensure that the value 'p' which has type 'Person' can be compared with another value which also has type 'Person'. I want the compiler to catch the error in those situations where the value being inserted is not an appropriate value.</p>
  
  <p>I can do something like this,</p>
  
  <pre><code>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 &amp;&amp; p.age &gt; v.age {
      return true
    }
    return false
  }
  </code></pre>
  
  <p>And then, within the "insert" function of the linked list I can use the <code>IsGreater</code> function to decide where to place the Element in the linked list. </p>
  
  <p>My question is...</p>
  
  <ol>
  <li>Is there a better way to do this? Something that is a lot better than the solution above.</li>
  </ol>
  
  <p>I've already gone through sort.Sort and seen how its done in that package. The way its done there is to create a new type for a slice of the type and then make that new type fulfill the sort interface by implementing Len, Less and Swap. </p>
  
  <p>I can probably do the same thing here in my case as well. But having to create a new slice type and then implement a few functions to satisfy an interface, when I'll only be dealing with 2 values of the same type at a time.. seems a bit overkill to me.</p>