On Fri, Oct 19, 2018 at 1:09 PM Ian Denhardt <i...@zenhack.net> wrote:
>
> Quoting Burak Serdar (2018-10-19 14:09:46)
>
> > It is useful in a linked list. You can instantiate a linked list
> > template in a package, and use that concrete type in another package
> > without access to the internals of the linked list.
>
> Can you provide an example of what some code using this would look like?
> The discussion in the abstract just isn't sticking to my brain...


I've been thinking about this for the last couple of hours, and I
have to admit, I got really close to giving up. Maybe a linked
list is not the best example to illustrate this. Anyway....

You would normally implement a linked list like this using parameterized types:

package linkedlist

type Node(type T) struct {
  next *Node(T)
  Stuff T
}

type LinkedList(type T) struct {
  head *Node(T)
}

func (l *LinkedList(T)) Add(n *Node(T)) {
  n.next=nil
  if l.head==nil {
    l.head=n
  } else {
    l.head.next=n
  }
}

func (l LinkedList(T)) Itr(f func(*Node(T))) {
  for node:=l.head;node!=nil;node=node.next {
    f(node)
  }
}


Then use this as:

var myList linkedlist.LinkedList(int)


However, using the "like" keyword, the following should also
be possible, which I think is more interesting than the above. I
needed something like this more than once during my Java days:

(this is different from the linkedlist I had earlier in the thread)

package linkedlist

// Define Node as a template that should satisfy the given struct contract
type Node like struct {
  next *Node
}

// LinkedList is a parameterized type, it will use nodes that look like a Node
type LinkedList(type T like(Node))  struct {
  head *T
}

// Do we need LinkedList(T)? Maybe not..
func (l *LinkedList) Add(n *Node) {
  n.next=nil
  if l.head==nil {
    l.head=n
  } else {
    l.head.next=n
  }
}

func (l LinkedList) Itr(f func(n *Node)) {
  for node:=l.head;node!=nil;node=node.next {
    f(node)
  }
}

package mypkg

type MyNode linkedList.Node {
  next *MyNode
  Stuff DataType
}

func f() {
  var myList linkedlist.LinkedList(MyNode)

  myList.Add(&MyNode{})
}


Let me know if this makes sense. There is still a lot that needs
to be figured out, and I wouldn't be surprised if the idea
collapses completely.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to