dongxiaofa6359 2016-04-12 07:12
浏览 6
已采纳

DeepEqual对待以反向滴答声初始化的数组是否有所不同?

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条回答 默认 最新

  • drd0833 2016-04-12 07:15
    关注

    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
    ", len(x), x)
    fmt.Printf("%d %q
    ", 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
    ", len(x), x)
    fmt.Printf("%d %q
    ", 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>.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line