1

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
  • Use reflect.TypeOf and call Name() on the result. Commented Sep 18, 2015 at 13:35

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.