types3.goΒΆ

// types3.go

package main

import (
    "fmt"
)

type Point struct {
    x, y float64
}

// interace{} has no required methods, and so all types implement it
func myPrint(arg interface{}) {
    // example of a type switch
    switch v := arg.(type) {
    case int:
        fmt.Printf("int=%v", v)
    case float32, float64:
        fmt.Printf("float=%v", v)
    case string:
        fmt.Printf("\"%v\"", v)
    case Point:
        fmt.Printf("(%v, %v)", v.x, v.y)
    default:
        fmt.Printf("???")
    } // switch
} // myPrint

func myPrintln(arg interface{}) {
    myPrint(arg)
    fmt.Println()
} // myPrint

func main() {
    myPrintln("cow")
    myPrintln(3.141)
    myPrintln(3141)
    myPrintln(Point{8, 2})
    myPrintln(true)

    var x interface{} = 5
    myPrintln(x)
    // the following lines won't compile due to a type error
    // y := x + 1
    // myPrintln(y)

    ix := x.(int) // type assertion
    y := ix + 1
    myPrintln(y)
} // main