时间:2021-07-01 10:21:17 帮助过:7人阅读
类型别名 是 Go 1.9 版本添加的新功能。主要应用于代码升级、工程重构、迁移中类型的兼容性问题。C/C++ 语言中,代码的重构升级可以使用宏快速定义新的代码。Go 语言中并未选择通过宏,而是选择通过类型别名解决重构中最复杂的类型名变更问题。
  type byte uint8
  type rune int32
  type byte = uint8
  type rune = int32
package main
import "fmt"
// 自定义类型myInt,基本类型是int
type myInt int
//将 int 类型取一个别名intAlias
type intAlias = int
func main() {
	//声明 a变量为自定义 myInt 类型
	var a myInt
	// 类型定义:依据基本类型声明一个新的数据类型。
	// 新声明一个变量c intAlias 类型
	var c intAlias
	c = a
	fmt.Printf("c Type: %T, value: %d\n", c, c)
	
OutPut Result:
 cannot use a (type myInt) as type int in assignment
从以上可以看出,变量 a 和 c 不是同一个类型,因此不能直接赋值;可以通过强制类型转换,实现 修改为 c=int(a)。