type关键
go type关键字主要用来进行自定义类型与声明类型别名
自定义类型格式 type 自定义类型名 原始类型名
代码
//自定义类型
type myInt int
以上代码是将int类型定义为myInt
类型别名格式 type 自定义类型名= 原始类型名 代码
//类型别名
type yourInt = int
此时yourInt是int类型的别名
测试代码package main
import "fmt"
//自定义类型
type myInt int
//类型别名
type yourInt = int
func (this myInt) sayHello() {
fmt.Println("我是自定义int")
}
func main() {
var age myInt = 13
fmt.Println("age = ", age)
age.sayHello()
//格式化输出需要使用Printf
//打印类型使用 %T
fmt.Printf("age type = %T\n", age)
fmt.Println("----------------------------")
var id yourInt = 1001
fmt.Println("id = ", id)
//格式化输出需要使用Printf
//打印类型使用 %T
fmt.Printf("id type = %T\n", id)
}
输出
age = 13
我是自定义int
age type = main.myInt
----------------------------
id = 1001
id type = int
可以看到myInt与your的类型不同,myInt的类型是main.myInt, yourInt是类型别名,它的类型是int. 自定义类型也可以像结构体一样,添加方法,例如上面的代码给myInt添加了方法sayHello().