dtvjl64442 2018-07-27 01:29
浏览 105
已采纳

类型<名称> <数据类型>和类型<名称> = <数据类型>之间的区别是什么

I'm new to Golang. I'm sorry but I'm still confused on what's the difference between:

type <Name> <dataType>

and

type <Name> = <dataType>

Here's an example:

package main

import "fmt"

func main() {
    var (
        strWord Word
        strText Text
    )
    strWord = "gopher"
    strText = "golang"

    fmt.Printf("strWord = %s, Type of Value = %T
", strWord, strWord)
    fmt.Printf("strText = %s, Type of Value = %T
", strText, strText)

}

type Word string

type Text = string

Output

strWord = gopher, Type of Value = main.Word
strText = golang, Type of Value = string

Then, when should we use between the two?

  • 写回答

1条回答 默认 最新

  • drnycqxwz63508434 2018-07-27 08:12
    关注

    The first is a type declaration, the second is a type alias

    Type declaration

    Docs: https://golang.org/ref/spec#Type_declarations

    This allows you to create a new distinct type <Name>, with the underlying type <datatype>.

    You could define something like:

    type Password string
    

    And then reimplement the String() method for it so that it's never accidentally printed.

    func (p Password) String() string {
        return "<redacted>"
    }
    

    Type alias

    Type aliases are used mostly for iterative refactoring, where moving a type from one package to another would create too large a change / break too many things.

    This article explains some usecases for it:

    https://talks.golang.org/2016/refactor.article

    But it essentially allows you to use one type as another.

    package mypackage
    type Foo struct {}
    
    
    package other
    type Bar = mypackage.Foo
    

    You can now use other.Bar and mypackage.Foo interchangeably. They are the same type, with different names. Whereas type declaration is a new type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 Ubuntu20.04无法连接GitHub
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥30 C++行情软件的tick数据如何高效的合成K线