您当前的位置: 首页 > 

令狐掌门

暂无认证

  • 0浏览

    0关注

    513博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

go自定义类型与类型别名

令狐掌门 发布时间:2022-04-01 11:38:57 ,浏览量:0

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().

关注
打赏
1652240117
查看更多评论
立即登录/注册

微信扫码登录

0.0370s