英文:
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("%d %q\n", len(x), x)
fmt.Printf("%d %q\n", len(y), y)
Output:
2 ["hello world" "me"]
3 ["hello" "world" "me"]
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`, "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))
Output:
3 ["hello" "world" "me"]
3 ["hello" "world" "me"]
true
Try these on the <kbd>Go Playground</kbd>.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论