Created
May 26, 2012 17:23
-
-
Save tetsuok/2794702 to your computer and use it in GitHub Desktop.
An example of type assertions for empty interface
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
| // An example of type assertions for empty interface (i.e., interface{}) | |
| package main | |
| import ( | |
| "container/list" | |
| "fmt" | |
| ) | |
| type Node struct { | |
| k string | |
| v float64 | |
| } | |
| func main() { | |
| { | |
| l := list.New() | |
| l.PushBack(Node{"Hello", -222.0}) | |
| l.PushBack(Node{"world", -42.1}) | |
| for e := l.Front(); e != nil; e = e.Next() { | |
| // Type assertions. | |
| n := e.Value.(Node) | |
| fmt.Printf("%T (k,v) = (%s,%g)\n", n, n.k, n.v) | |
| } | |
| } | |
| // reference types | |
| { | |
| rl := list.New() | |
| rl.PushBack(&Node{"Hello", -222.0}) | |
| rl.PushBack(&Node{"world", -42.1}) | |
| for e := rl.Front(); e != nil; e = e.Next() { | |
| // Type assertions. | |
| n := e.Value.(*Node) // pointer to Node | |
| fmt.Printf("%T (k,v) = (%s,%g)\n", n, n.k, n.v) | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also http://golang.org/ref/spec#Type_assertions