I’ve the next code which is an train from right here (A Tour of Go).
bundle primary
import (
"errors"
"fmt"
)
// Record represents a singly-linked checklist that holds
// values of any kind.
kind Record[T any] struct {
subsequent *Record[T]
val T
}
func (head Record[T]) my_next() (T, error) {
if head.subsequent == nil {
// QUESTION ABOUT THIS LINE
return head.val, errors.New("no subsequent component")
}
return head.subsequent.val, nil;
}
func primary() {
l := Record[int]{nil, 123};
fmt.Println(l.my_next());
}
The my_next methodology is meant to get the subsequent component within the linked checklist. If we’re on the tail, it ought to return a non-nil error.
If head.subsequent == nil
, then we actually shouldn’t returning something for the worth (we must always solely return an error). I attempted return nil, errors.New("no subsequent component")
however that might not compile. Briefly, this case labored out as a result of I can simply return head.val
as a dummy/placeholder worth which I do know is of kind T.
Is there any manner I can assemble a default of/for kind T any?
Perhaps I’m in search of a “constructable” or “defaultable” interface or one thing comparable?
Very new to go, any and all assistance is appreciated!
You may do one thing like this:
if head.subsequent == nil {
var empty T
return empty, errors.New("no subsequent component")
}
I figured I used to be lacking one thing easy like that. Thanks a lot to your assist!