douju5062 2015-09-18 13:21
浏览 59
已采纳

如何在Go中打印数组项的类型?

When I try to unit test some code, I have some assertion like this:

expected := []interface{}{1}
actual := []interface{}{float64(1)}

if !reflect.DeepEqual(expected, actual); {
    t.Errorf("Expected <%T> %#v to equal <%T> %#v", actual, actual, expected, expected);
}

And got this output:

Expected <[]interface {}> []interface {}{1} to equal <[]interface {}> []interface {}{1}

How can I print this message to be more explicit?

Thanks!

see this code in play.golang.org
  • 写回答

1条回答 默认 最新

  • doukuang8166 2015-09-18 13:58
    关注

    You are printing the types of the slices, not the types of the elements. And types of the slices are []interface{}. That's why you see that.

    If you want to see the dynamic types of the elements (their static type is always interface{}), then print the types of the elements:

    fmt.Printf("Expected element type: %T, got: %T", expected[0], actual[0])
    

    Which will output:

    Expected element type: int, got: float64
    

    Note:

    The above code assumes you are comparing 2 slices with 1 element. If you don't want to check slice length and you want to handle slices with any length, you can use other verbs. For example you can use the %t verb which expects a bool value and wants to print true or false. Note that this is just an implementation decision and not guaranteed, but using %t for example will print all the slice elements; printing the respective bool value if it is of type bool, and will print the dynamic type and value of the element if the it is not of type bool.

    Example:

    data := []interface{}{1, float64(2), "3", time.Now()}
    fmt.Printf("%t", data)
    

    Output:

    [%!t(int=1) %!t(float64=2) %!t(string=3)
        {%!t(int64=63393490800) %!t(int32=0) %!t(*time.Location=&{ [] [] 0 0 <nil>})}]
    

    It's a bit ugly, but contains many useful info (e.g. types, values).

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

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作