This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| snippets:golang:interface [2018/03/20 11:42] – created allspark | snippets:golang:interface [2018/03/20 11:46] (current) – allspark | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ## interface | ||
| + | ```go | ||
| + | package main | ||
| + | |||
| + | import " | ||
| + | |||
| + | type A struct { | ||
| + | A int | ||
| + | } | ||
| + | |||
| + | type B struct { | ||
| + | B int | ||
| + | } | ||
| + | |||
| + | func Print(i interface{}) { | ||
| + | switch v := i.(type) { | ||
| + | case A: | ||
| + | fmt.Println(" | ||
| + | case B: | ||
| + | fmt.Println(" | ||
| + | } | ||
| + | } | ||
| + | |||
| + | func main() { | ||
| + | a := A{5} | ||
| + | b := B{42} | ||
| + | |||
| + | Print(a) | ||
| + | Print(b) | ||
| + | } | ||
| + | ``` | ||
| + | |||
| + | |||
| + | ## output | ||
| + | |||
| + | < | ||
| + | ``` | ||
| + | A: 5 | ||
| + | B: 42 | ||
| + | ``` | ||
| + | </ | ||