I have the following code which is an exercise from here (A Tour of Go).
package main
import (
"errors"
"fmt"
)
// List represents a singly-linked list that holds
// values of any type.
type List[T any] struct {
next *List[T]
val T
}
func (head List[T]) my_next() (T, error) {
if head.next == nil {
// QUESTION ABOUT THIS LINE
return head.val, errors.New("no next element")
}
return head.next.val, nil;
}
func main() {
l := List[int]{nil, 123};
fmt.Println(l.my_next());
}
The my_next method is supposed to get the next element in the linked list. If we are at the tail, it should return a non-nil error.
If head.next == nil
, then we really shouldn’t returning anything for the value (we should only return an error). I tried return nil, errors.New("no next element")
but that would not compile. In short, this case worked out because I can just return head.val
as a dummy/placeholder value which I know is of type T.
Is there any way I can construct a default of/for type T any?
Maybe I’m looking for a “constructable” or “defaultable” interface or something similar?
Very new to go, any and all help is appreciated!