Last active
December 31, 2015 15:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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