Golang中的类型声明和类型定义有什么区别? [英] What is the difference between type Declaration and type Definition in Golang?

查看:52
本文介绍了Golang中的类型声明和类型定义有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型声明:

type A = string

类型定义:

type A string

它们之间有什么区别?我从规范中无法理解

What is the difference between them? I can't understand from spec

推荐答案

类型A =字符串 string 创建别名.每当您在代码中使用 A 时,其工作方式就与 string 一样.因此,例如,您无法在其上定义方法.

type A = string creates an alias for string. Whenever you use A in your code, it works just like string. So for example, you can't define methods on it.

类型字符串定义了一个新类型,该类型具有与 string 相同的表示形式.您可以以零成本在 A string 之间进行转换(因为它们相同),但是您可以在新类型上定义方法,并且反射将知道该类型 A .

type A string defines a new type, which has the same representation as string. You can convert between an A and string at zero cost (because they are the same), but you can define methods on your new type, and reflection will know about the type A.

例如(在游乐场上)

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

这篇关于Golang中的类型声明和类型定义有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆