`struct{a int;b int}`和`struct{b int;a int}`之间有什么区别?

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

What is the difference between struct{a int;b int} and struct{b int;a int}?

问题

这两个结构体之间除了它们不被认为是等价的之外,还有什么区别?

package main

func main() {}
func f1(s struct{a int;b int}) { f2(s) }
func f2(s struct{b int;a int}) {}

注意:这段代码无法编译通过:

$ go run a.go 
# command-line-arguments
./a.go:3: cannot use s (type struct { a int; b int }) as type struct { b int; a int } in argument to f2

但是,这段代码可以编译通过:

package main

func main() {}
func f1(s struct{a int;b int}) { f2(s) }
func f2(s struct{a int;b int}) {}
英文:

What is the difference between these two structs other than that they aren't considered equivalent?

package main
func main() {}
func f1(s struct{a int;b int}) { f2(s) }
func f2(s struct{b int;a int}) {}

<!

$ go run a.go 
# command-line-arguments
./a.go:3: cannot use s (type struct { a int; b int }) as type struct { b int; a int } in argument to f2

Note: this does compile:

package main
func main() {}
func f1(s struct{a int;b int}) { f2(s) }
func f2(s struct{a int;b int}) {}

答案1

得分: 5

“结构体字段的顺序在低级别上是重要的”是什么意思?

这将影响到反射,比如func (v Value) Field(i int) Value

Field 返回结构体 v 的第 i 个字段

第一个结构体中的字段'a'在第二个结构体中不会是同样的第一个字段。
这也会影响到使用编组方法(encoding 包)进行序列化

英文:

> "The order of structs' fields is important on the low level" How?

This will impact the reflection, like func (v Value) Field(i int) Value:

> Field returns the i'th field of the struct v

The first field 'a' in the first structure wouldn't be the same first in the second structure.
That also will influence serialization with marshaler methods (encoding package).

答案2

得分: 4

类型和值的属性

类型标识

如果两个结构类型具有相同的字段序列,并且相应的字段具有相同的名称、相同的类型和相同的标签,则它们是相同的。

相应的字段名称不同:

s struct{a int;b int}

s struct{b int;a int}
英文:

> Properties of types and values
>
> Type identity
>
> Two struct types are identical if they have the same sequence of
> fields, and if corresponding fields have the same names, and identical
> types, and identical tags.

The corresponding field names differ:

s struct{a int;b int}

versus

s struct{b int;a int}

答案3

得分: 3

根据规范

如果两个结构体类型具有相同的字段序列,并且相应的字段具有相同的名称、相同的类型和相同的标签,则它们是相同的。两个匿名字段被认为具有相同的名称。不同包中的小写字段名称始终是不同的。

结构体字段的顺序在底层是重要的,因此具有不同字段顺序的两个结构体不能被安全地视为等价。

英文:

From the spec:

>Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Two anonymous fields are considered to have the same name. Lower-case field names from different packages are always different.

The order of structs' fields is important on the low level, so two structs with different sequence of fields cannot be safely considered equivalent.

huangapple
  • 本文由 发表于 2014年8月26日 22:46:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/25508759.html
匿名

发表评论

匿名网友

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

确定