自定义类型
使用关键字 来声明:
- 单次声明
type City string
- 批量声明
package main
type City string
func main() {
city := City("上海")
}
package main
import "fmt"
type Age int
func main() {
middle := Age(12)
}
func printAge(age int) {
fmt.Println("Age is", age)
}
当我们运行代码的时候会出现 ./main.go:11:10: cannot use middle (type Age) as type int in argument to printAge
的错误。
我们可以采用显式的类型转换( printAge(int(primary))
)来修复。