我是果朗的新手。很抱歉,但我仍然对之间的区别感到困惑
type <Name> <dataType>
和
type <Name> = <dataType>
这里有一个例子:
package main
import "fmt"
func main() {
var (
strWord Word
strText Text
)
strWord = "gopher"
strText = "golang"
fmt.Printf("strWord = %s, Type of Value = %Tn", strWord, strWord)
fmt.Printf("strText = %s, Type of Value = %Tn", strText, strText)
}
type Word string
type Text = string
输出
strWord = gopher, Type of Value = main.Word
strText = golang, Type of Value = string
那么,我们什么时候应该在两者之间使用呢?
第一个是类型声明,第二个是类型别名
类型声明
文档:https://golang.org/ref/spec#Type_declarations
这允许您创建一个新的具有基础类型<datatype>
的不同类型<Name>
。
你可以定义如下:
type Password string
然后重新实现它的String()
方法,这样它就不会意外打印出来。
func (p Password) String() string {
return "<redacted>"
}
类型别名
类型别名主要用于迭代重构,在迭代重构中,将类型从一个包移动到另一个包会产生太大的更改/破坏太多内容。
本文解释了它的一些用例:
https://talks.golang.org/2016/refactor.article
但它本质上允许您将一种类型用作另一种类型。
package mypackage
type Foo struct {}
package other
type Bar = mypackage.Foo
现在,您可以互换使用other.Bar
和mypackage.Foo
。它们是同一类型,有不同的名称。而类型声明是一个新的类型。