Go 的 类型定义 和 类型别名 (Type Alias Declarations)
2021-08-18 00:06
519 查看
type A = B // type alias 仅仅是一个 alias (别名), 没有生成一个新的 type,因此不需要强转型 type A B // type definition, 将会产生一个新的 type, 在进行类型变换时,需要强转型
package main import "fmt" type A = int type B int func main() { var a A var b B var i int a = i b = B(i) fmt.Println(a, b) }
使用 type alias 之后,不一定能为该 type alias 添加 method。
例如在上面 A 是 int 的 alias,也就是说 A 实际上就是 int,int 是一个 built in type ,在 go 中没办法为 build in type 添加 alias。
func (A) Hello() { // Error : Cannot define new methods on the non-local type 'builtin.int' } func (B) Hello() { // It's OK }
type alias 和它的本体的 method 定义是共享的
package main import "fmt" type B int type AliasB = B func (B) Hello() { fmt.Println("hello") } // func (AliasB) Hello() { // // Error: Method redeclared 'AliasB.Hello' // } func (AliasB) World() { fmt.Println("world") } func main() { var b B var aliasB AliasB b.Hello() // ok b.World() // ok aliasB.Hello() // ok aliasB.World() // ok }
method 的 receiver 的 type 不能是 pointer, 因此下面两种做法都是编译不过的
type B int type AliasB = B type AliasPointerB = *B type PointerB *B func (PointerB) Hello() { // Error: Invalid receiver type 'PointerB' ('PointerB' is a pointer type) } func (AliasPointerB) PHello() { // Error: Invalid receiver type 'AliasPointerB' ('AliasPointerB' is a pointer type) }
btw,
byte是
uint8的 alias ,
rune是
int32的 alias
reference: https://go101.org/article/type-system-overview.html
相关文章推荐
- Kotlin-37.类型别名(typealias)
- Go语言学习笔记 --- 常量、变量、批量定义与声明、数据类型、类型别名、类型转换
- MyBatis源码解析(八)——Type类型模块之TypeAliasRegistry(类型别名注册器)
- mybatis-TypeAliasRegistry--类型别名注册
- [译]有关Kotlin类型别名(typealias)你需要知道的一切
- Mybatis源码之(TypeAliasRegistry)TypeAlias别名实现机制
- MyBitis(iBitis)系列随笔之二:类型别名(typeAliases)与表-对象映射(ORM)
- 类型化(Type)的DataSet (使用强类型的DataSet。定义的数据库表一定要有主键,否则不能使用)
- python 函数定义和内置函数isinstance以及数据类型检查type的使用
- Android中EditText中的InputType类型含义与如何定义
- 1.3.11 - [defns.static.type] - 【定义.静态.类型】
- linux alias命令参数及用法详解--linux定义命令别名alias
- MyBitis(iBitis)系列随笔之二:类型别名(typeAliases)与表-对象映射(ORM)
- Mybatis源码之(TypeAliasRegistry)TypeAlias别名实现机制
- type类型定义
- linux alias命令参数及用法详解--linux定义命令别名alias
- 初学XML(2) DTD(Document type defintnion)文档类型定义
- ubuntu定义别名(alias)
- Mybatis 内置 Java 类型别名与 typeHandlers
- Solr字段类型field type的定义