结构体创建:声明和表达式之间有什么区别吗?

huangapple go评论68阅读模式
英文:

Struct creation: Is there a difference between declaration and expression?

问题

在我的测试中,这两个似乎表现得一样:

// 声明
type Decl struct { }

// 表达式
type Expr = struct { }

我似乎在规范中找不到与此相关的内容。

英文:

In my testing, these 2 seem to behave the same way:

// declaration
type Decl struct { }

// expression
type Expr = struct { }

I can't seem to find anything in the spec that pertains to this specifically.

答案1

得分: 2

根据类型声明的说明,没有等号的语法(type A B)定义了一个独立的类型,而有等号的语法(type A = B)定义了一个别名

例如:

type A struct{}

type B = struct{}

func (a A) String() string {
    return "A"
}

// 无法编译通过:无效的接收者类型 struct{}
// func (b B) String() string {
//     return "B"
// }

别名与其源类型等效,除了名称不同,这会影响结构体中的嵌入

英文:

According to Type declarations, the syntax without an equal sign (type A B) defines a distinct type, while the other one (type A = B) defines an alias.

See for example:

type A struct{}

type B = struct{}

func (a A) String() string {
    return "A"
}

// Does not compile: invalid receiver type struct{}
// func (b B) String() string {
//     return "B"
// }

An alias is equivalent to its source type, except for a different name, which affects embedding in structs.

huangapple
  • 本文由 发表于 2023年7月13日 01:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定