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?

图片转代码服务由CSDN问答提供 功能建议

我的问题很简单,我使用倒钩启动字符串数组,但是我发现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] 
false 
   
 
 

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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 Go Playground.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题