json2.go 696 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "fmt"
  7. "math"
  8. )
  9. func InterfaceExample() {
  10. var i interface{}
  11. i = "a string"
  12. i = 2011
  13. i = 2.777
  14. // STOP OMIT
  15. r := i.(float64)
  16. fmt.Println("the circle's area", math.Pi*r*r)
  17. // STOP OMIT
  18. switch v := i.(type) {
  19. case int:
  20. fmt.Println("twice i is", v*2)
  21. case float64:
  22. fmt.Println("the reciprocal of i is", 1/v)
  23. case string:
  24. h := len(v) / 2
  25. fmt.Println("i swapped by halves is", v[h:]+v[:h])
  26. default:
  27. // i isn't one of the types above
  28. }
  29. // STOP OMIT
  30. }
  31. func main() {
  32. InterfaceExample()
  33. }