Source file
doc/progs/json2.go
1
2
3
4
5 package main
6
7 import (
8 "fmt"
9 "math"
10 )
11
12 func InterfaceExample() {
13 var i interface{}
14 i = "a string"
15 i = 2011
16 i = 2.777
17
18
19
20 r := i.(float64)
21 fmt.Println("the circle's area", math.Pi*r*r)
22
23
24
25 switch v := i.(type) {
26 case int:
27 fmt.Println("twice i is", v*2)
28 case float64:
29 fmt.Println("the reciprocal of i is", 1/v)
30 case string:
31 h := len(v) / 2
32 fmt.Println("i swapped by halves is", v[h:]+v[:h])
33 default:
34
35 }
36
37
38 }
39
40 func main() {
41 InterfaceExample()
42 }
43
View as plain text