Go类型别名与类型定义区别

类型别名和自定义类型区别

自定义类型

//自定义类型是定义了一个全新的类型
//将MyInt定义为int类型
type MyInt int

类型别名

//类型别名规定:TypeAlias只是Type的别名,本质上TypeAlias与Type是同一个类型。
type TypeAlias = Type
type byte = uint8
type rune = int32

区别

类型别名与类型定义表面上看只有一个等号的差异

//类型定义
type NewInt int

//类型别名
type MyInt = int

func main() {
    var a NewInt
    var b MyInt
    
    fmt.Printf("type of a:%T\n", a) //type of a:main.NewInt
    fmt.Printf("type of b:%T\n", b) //type of b:int
}
//区别
//结果显示a的类型是main.NewInt,表示main包下定义的NewInt类型。b的类型是intMyInt类型只会在代码中存在,编译完成时并不会有MyInt类型。

猜你喜欢

转载自www.cnblogs.com/Paul-watermelon/p/11100854.html
今日推荐