如何在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

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).