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 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件