Skip to content

Instantly share code, notes, and snippets.

@skriticos
Last active December 31, 2015 15:09
Show Gist options
  • Save skriticos/6f14b12605091d4846a2 to your computer and use it in GitHub Desktop.
Save skriticos/6f14b12605091d4846a2 to your computer and use it in GitHub Desktop.
golang control flow in a linked list based on element type using type assertion
// go control flow in a linked list based on element type using type assertion
package main
import (
"fmt"
"reflect"
"container/list"
)
type Foo struct {
x, y string
}
type Bar struct {
a, b int
}
func main() {
l := list.New()
l.PushBack(Foo{"hello", "there"})
l.PushBack(Bar{1, 2})
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println("iterating type:", reflect.TypeOf(e.Value))
// we only go here if the element has type main.Foo
v, ok := e.Value.(Foo)
if ok {
fmt.Println("type conditional value access:", v.x, v.y)
}
}
}
// Output:
// iterating type: main.Foo
// type conditional value access: hello there
// iterating type: main.Bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment