自定义类型

    使用关键字 来声明:

    • 单次声明
    1. type City string
    • 批量声明
    1. package main
    2. type City string
    3. func main() {
    4. city := City("上海")
    5. }
    1. package main
    2. import "fmt"
    3. type Age int
    4. func main() {
    5. middle := Age(12)
    6. }
    7. func printAge(age int) {
    8. fmt.Println("Age is", age)
    9. }

    当我们运行代码的时候会出现 ./main.go:11:10: cannot use middle (type Age) as type int in argument to printAge 的错误。

    我们可以采用显式的类型转换( printAge(int(primary)))来修复。