类型别名:
type A = string
类型定义:
type A string
它们之间有什么区别?从规范上我看不懂。
类型别名:
type A = string
类型定义:
type A string
type A = string
创建了一个string
的别名A
。当你在代码中使用A
时,它的作用与string
相同。例如,你不能在其上定义方法。
type A string
定义了一个新类型,其表示方式与string
相同。你可以在A
和string
之间进行零成本转换(因为它们是相同的),但是你可以在新类型上定义方法,并且反射会知道类型A
。
例如(在playground上)
package main
import (
"fmt"
)
type A = string
type B string
func main() {
var a A = "hello"
var b B = "hello"
fmt.Printf("a is %T\nb is %T\n", a, b)
}
输出:
a is string
b is main.B
像字符串一样。例如,你不能在其上定义方法
--我建议为了清晰表达重写它。 - Grigoriy Mikhalkin明确术语,这两个都是类型声明。
type A = string
type A struct {}
type B = A
func (B) print() {
fmt.Println("B")
}
func main() {
a := A{}
b := B{}
a.print() // OUTPUT: B
b.print() // OUTPUT: B
}
type A = string
,你无法定义它的方法,因为string是非本地类型(曾经有一个提案添加为非本地类型创建方法的能力,但被拒绝了)。type A string
是类型定义。基本上,它创建了一个具有原始类型所有字段但没有其方法的新类型。示例:type A struct {}
func (A) print() {
fmt.Println("A")
}
type B A
func (B) print() {
fmt.Println("B")
}
func main() {
a := A{}
b := B{}
a.print() // OUTPUT: A
b.print() // OUTPUT: B
}
type A = string
表示创建了两者之间的别名,它们在这个阶段是不能被扩展的。这样做有什么作用呢?对于 golang 来说,它们有助于进行代码库重构和修复,这里有一篇很棒的文章:https://talks.golang.org/2016/refactor.article。
类型定义允许您在需要时将某个类型扩展为具有额外行为的类型,这通常是开发人员构建自定义数据类型所需的最有用的方法。
type A = string
var myString A
type A string
这是定义一种类型。
它非常类似于定义一个变量。
var randomNumber int
在这里,'A'是一个新类型。但是您可以通过向其添加新方法来操作新定义的类型A。