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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献