1

I'm trying to implement a linked list with a generic data type and I created a method new() which creates a list with a nil root and length = 0. Now the problem is how do I initialize the list in the main function.

type Node[T any] struct {
    data T
    next *Node[T]
}

type LinkedList[T any] struct {
    root   *Node[T]
    length uint
}

func (list *LinkedList[T]) new() *LinkedList[T] {
    return &LinkedList[T]{root: nil, length: 0}
}
func main() {
    list := LinkedList[int].new()
}

This is what I tried to do which gives "cannot call pointer method new on LinkedList[int]".

2 Answers2

2
func (list *LinkedList[T]) new() *LinkedList[T]

This is a method which will only exist on an already initialized instance of LinkedList[T]. So it doesn't make a ton of sense to do as a method as you'll have to create a LinkedList[T] to call new on it before you can get a *LinkedList[T]

You could do this:

    l := &LinkedList[int]{}
    l = l.new()

But since new() just explicity sets fields to their zero values, you ay as well just:

    l := &LinkedList[int]{}
erik258
  • 14,701
  • 2
  • 25
  • 31
1

The answer from erik258 is correct. As he mentioned in the final part of his answer, since the zero values are valid initial values, you should just initialize a LinkedList using a struct literal. No constructor or initializer function is needed.

However, just in case anyone who finds this question later is wondering how initializing constructors can be written for generic types in Go I thought I would add that.

Here's an answer with more info on the topic of constructors. They are also mentioned in Effective Go.

Building on that answer, here's how you can write a constructor for the generic type from your question:

func NewLinkedList[T any]() *LinkedList[T] {
   return &LinkedList[T]{root: nil, length: 0}
}

Here's that code running in Go Playground.

phonaputer
  • 1,485
  • 4
  • 9