Reputation: 5260
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?
Upvotes: 0
Views: 50
Reputation: 417592
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 Go Playground.
Upvotes: 5