How to make a variable with this data type and value in Golang? Pointer to a struct with a nil value?

I am doing a unit test, but I found this data type that I don't understand.

Error:          
       Not equal: 
                 expected: <nil>(<nil>)
                 actual  : *pkgname.StructName((*pkgname.StructName)(nil))

FYI, pkgname is a name of a package, StructName is a name of a Struct

How do I make a variable with the same datatype and value of "*pkgname.StructName((*pkgname.StructName)(nil))"?

Is it a pointer of struct to a nil value?


Solution 1:

You don't mention which testing framework or method you use, but judging from the error, most certainly the mistake is that you expect a nil value (without type), and you get a nil pointer value which has a pointer type with a concrete base type.

To fix it, you should expect a typed nil value, and not a nil interface value (without type).

For example:

actualValue := ... // Execute function / method / whatever, obtain testable value

// Test it the way you do
// (Here I assume you do it with a function named expectEqual):
expectEqual((*pkgname.StructName)(nil), actualValue)

Note that (*pkgname.StructName)(nil) is a type conversion, it converts the nil (pointer) value to *pkgname.StructName pointer type.

See related questions:

Convert nil interface to pointer of something in Golang?

Hiding nil values, understanding why golang fails here