DeepEqual对使用反引号初始化的数组有不同的处理方式吗?

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

DeepEqual treats array initialized with back tick differently?

问题

我的问题很简单,我使用反引号来初始化一个字符串数组,但我发现golang对待这个数组的方式不同:

import (
	"fmt"
	"reflect"
)

func main() {
	x := []string{`hello world`, "me"}
	y := []string{"hello", "world", "me"}
	fmt.Println(x)
	fmt.Println(y)
	fmt.Println(reflect.DeepEqual(x, y))
}

输出结果为:

[hello world me]
[hello world me]
false

这让我感到困惑:我应该确保所有的字符串数组都以相同的方式初始化吗?

英文:

My question is quite simple, I use back tick to initiate a string array, but I found that golang treats this array differently:

import (
	"fmt"
	"reflect"
)

func main() {
	x := []string{`hello world`, "me"}
	y := []string{"hello", "world", "me"}
	fmt.Println(x)
	fmt.Println(y)
	fmt.Println(reflect.DeepEqual(x, y))
}

The output is:

[hello world me]
[hello world me]
false

This makes me confused: should I make sure all string arrays are initiated in the same way?

答案1

得分: 5

这些是切片(slices),而不是数组(arrays),你的第一个切片有2个元素,第二个切片有3个元素,所以它们怎么可能相等呢?

尝试像这样打印它们:

fmt.Printf("%d %q\n", len(x), x)
fmt.Printf("%d %q\n", len(y), y)

输出结果:

2 ["hello world" "me"]
3 ["hello" "world" "me"]

fmt.Println()会打印传入切片的所有值,在元素之间打印一个空格。而x的第一个元素是一个字符串,它等于y的前两个元素用空格连接起来,这就是为什么你看到切片的打印内容相等。

当你使用相同的3个字符串用反引号初始化你的第一个切片时,它们将是相等的:

x = []string{`hello`, `world`, "me"}
y = []string{"hello", "world", "me"}
fmt.Printf("%d %q\n", len(x), x)
fmt.Printf("%d %q\n", len(y), y)
fmt.Println(reflect.DeepEqual(x, y))

输出结果:

3 ["hello" "world" "me"]
3 ["hello" "world" "me"]
true

在<kbd>Go Playground</kbd>上尝试一下这些代码。

英文:

Those are slices, not arrays, and your first slice has 2 elements, and the second has 3 elements, so how could they be equal?

Try printing them like this:

fmt.Printf(&quot;%d %q\n&quot;, len(x), x)
fmt.Printf(&quot;%d %q\n&quot;, len(y), y)

Output:

2 [&quot;hello world&quot; &quot;me&quot;]
3 [&quot;hello&quot; &quot;world&quot; &quot;me&quot;]

fmt.Prinln() will print all values of the passed slice, printing a space between elements. And first element of x is a string which equals to the first 2 elements of y joined with a space, that's why you see equal printed content for the slices.

When you use the same 3 strings to initialize your first slice with backticks, they will be equal:

x = []string{`hello`, `world`, &quot;me&quot;}
y = []string{&quot;hello&quot;, &quot;world&quot;, &quot;me&quot;}
fmt.Printf(&quot;%d %q\n&quot;, len(x), x)
fmt.Printf(&quot;%d %q\n&quot;, len(y), y)
fmt.Println(reflect.DeepEqual(x, y))

Output:

3 [&quot;hello&quot; &quot;world&quot; &quot;me&quot;]
3 [&quot;hello&quot; &quot;world&quot; &quot;me&quot;]
true

Try these on the <kbd>Go Playground</kbd>.

huangapple
  • 本文由 发表于 2016年4月12日 15:12:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/36566080.html
匿名

发表评论

匿名网友

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

确定