英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论