types1.goΒΆ

// types1.go

package main

import (
    "fmt"
)

// Number is a brand new type; it is *not* just a synonym for int.
// Number has the same representation as an int
type Number int

// a function
func isOdd(n Number) bool {
    return n%2 == 1
}

// a method
func (n Number) isEven() bool {
    return n%2 == 0
}

func test1() {
    var n Number = 5
    fmt.Println(n)

    // compiler error: can't assign n to x
    // var x int = n
    // fmt.Println(x)

    if isOdd(n) {
        fmt.Printf("%v is odd\n", n)
    }

    if n.isEven() {
        fmt.Printf("%v is even\n", n)
    }
} // test1

// Integer is a brand new type whose underlying representation is the same as
// an int
type Integer int

func test2() {
    var i Integer = 6
    var n Number = 5
    fmt.Println(i, n)

    // The following lines are type errors caught by the compiler
    // i = n
    // n = i

    i = Integer(n) // okay

    fmt.Println(i)
} // test2

func main() {
    test1()
    test2()
} // main