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

异同点

二者都是使用type关键字定义, 写法不同:

  • 类型定义:type MyInt int
  • 类型别名:type IntAlias = int

使用场景

类型别名是go 1.9以后引入的新功能,主要是为了解决代码升级迁移中的兼容问题

  • 类型别名只存在与代码中,编译后别名是不存在的, 见实例1代码
  • 类型别名不可随意扩充方法,类型定义可以在新的类型上扩充自定义方法,见实例2
// 实例1 
package main

import "fmt"

// 将MyInt 定义为int类型
type MyInt int

// 将int取一个别名 IntAlias
type IntAlias = int

func testAlias() {
	var a MyInt
	fmt.Printf("a type:%T \n", a)	// a type:main.MyInt

	var b IntAlias
	fmt.Printf("b type:%T \n", b)	// b type:int
}

// 实例2 
package main

import (
	"fmt"
	"time"
)

type myDuration = time.Duration		// 此处改为类型可通过编译即 type myDuration time.Duration

func (d myDuration) getSeconds() int {	// 编译错误,cannot define new methods on non-local type time.Duration(不能在非本地的类型time.Duration上定义新方法)
	return 1
}

func testType() {
	var d myDuration
	fmt.Println(d.getSeconds())
}


type 关键字其他用法

  1. 定义结构体
    type MyStruct struct {}
    
  2. 定义接口
    type MyInterface interface {}
    
  3. 类型定义
    type myInt int
    
  4. 类型别名
    type IntAlias = int
    
  5. 类型查询
    var data interface{}
    switch data.(type) {
    	case int:
    	// ……
    }
    

你可能感兴趣的:(Golang,golang,类型定义,alias,类型别名)