I'd like to implement a linked list with nodes. Each node can be of a different type (Foo, Bar and Baz - will be 40-50 different nodes) and each type has common fields (prev, next, ...) and some node-specific fields.
I have a hard time to come up with a solution that looks reasonable. Now the question: what approach can I take to make this more elegant?
Here is my (dummy) main.go
:
package main
import (
"fmt"
"node"
)
func main() {
a := node.NewFoo()
fmt.Println(a)
b := node.NewBar()
fmt.Println(b)
node.Append(a, b)
}
and here is my implementation (node.go
):
package node
type Node interface {
}
type FooNode struct {
prev Node
next Node
FieldSpecificToFoo int
}
type BarNode struct {
prev Node
next Node
FieldSpecificToBar int
}
type BazNode struct {
prev Node
next Node
FieldSpecificToBaz int
}
func NewFoo() *FooNode {
return &FooNode{}
}
func NewBar() *BarNode {
return &BarNode{}
}
func NewBaz() *BazNode {
return &BazNode{}
}
func Append(a, b Node) {
// set next and prev pointer
switch v := a.(type) {
case FooNode:
v.next = b
case BarNode:
v.next = b
case BazNode:
v.next = b
}
switch v := b.(type) {
case FooNode:
v.prev = a
case BarNode:
v.prev = a
case BazNode:
v.prev = a
}
}
This is obviously a pretty crappy implementation. What can I do in this case?