Go:比较匿名结构体

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

Go: comparing anonymous structs

问题

我不理解go如何比较匿名结构体。我正在尝试理解这段代码:

package main

import (
	"fmt"
)

type foo struct {
	bar string
}

func main() {
	var x struct {
		bar string
	}
	var y foo
	fmt.Println(x == y) // 这将打印出 true
	equals(x, y) // 这将打印出 false

}


func equals(a, b interface{}) {
	fmt.Println(a == b)
}

为什么x == y的结果是true?它们具有不同的类型,所以我本以为它们不能进行比较。

而且,既然它们是相等的,为什么将它们转换为interface{}后它们变得不相等?

英文:

I don't understand how go compares anonymous structures. I am trying to understand this piece of code:

package main

import (
	"fmt"
)

type foo struct {
	bar string
}

func main() {
	var x struct {
		bar string
	}
	var y foo
	fmt.Println(x == y) // this prints true
	equals(x, y) // this prints false

}


func equals(a, b interface{}) {
	fmt.Println(a == b)
}

Why does x == y yields true? They have a different type, so I would expect that they cannot be compared.

And, as they are equal, why casting them to interface{} makes them unequal?

答案1

得分: 6

为什么 x == y 的结果是 true?

根据 Go 语言规范中的说明:

如果结构体的所有字段都是可比较的,那么结构体值就是可比较的。如果两个结构体值的对应非空字段相等,那么这两个结构体值就相等。

对于 string 类型的零值是 "",所以 x.bary.bar 是相等的,因此 xy 是相等的。


为什么将它们转换为 interface{} 后它们不相等?

同样,根据语言规范中的同一页说明:

接口值是可比较的。如果两个接口值具有相同的动态类型和相等的动态值,或者两个接口值都是 nil,则它们是相等的。

英文:

>Why does x == y yields true?

From the Go language specification:

>Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

The zero-value for a string is "", so x.bar and y.bar are equal, and therefore x and y are equal.


>why casting them to interface{} makes them unequal?

Again, from the same page in the language specification:

>Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

答案2

得分: 2

它们具有不同的类型,但是由于结构体具有相同的字段名称/类型,它们是可比较的。如果尝试重命名字段,它将无法编译。

它们作为interface{}值是可比较的,但它们的动态类型是不同的-你可以使用fmt的%T动词来检查。

http://play.golang.org/p/x0w30RIb5a

英文:

They have a different type but are comparable since the structs have the same field names/types. If you try renaming the field, it won't compile.

They are comparable as interface{} values, but their dynamic types are different - You can check this with the fmt %T verb

http://play.golang.org/p/x0w30RIb5a

huangapple
  • 本文由 发表于 2016年4月19日 21:28:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/36719925.html
匿名

发表评论

匿名网友

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

确定