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

huangapple go评论97阅读模式
英文:

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

问题

我正在进行单元测试,但我发现了一个我不理解的数据类型。

错误信息:
不相等:
期望值:<nil>(<nil>)
实际值:*pkgname.StructName((*pkgname.StructName)(nil))

FYI,pkgname是一个包的名称,StructName是一个结构体的名称。

如何创建一个与"*pkgname.StructName((*pkgname.StructName)(nil))"具有相同数据类型和值的变量?

它是一个指向nil值的结构体指针吗?

英文:

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

Error:      	
       Not equal: 
                 expected: &lt;nil&gt;(&lt;nil&gt;)
        	     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?

答案1

得分: 3

你没有提到你使用的测试框架或方法,但根据错误判断,错误很可能是你期望一个没有类型的nil值,而实际上你得到了一个具有指针类型和具体基础类型的nil指针值。

要修复这个问题,你应该期望一个有类型的nil值,而不是一个没有类型的nil接口值。

例如:

actualValue := ... // 执行函数/方法/其他操作,获取可测试的值

// 以你的方式进行测试
// (这里假设你使用名为expectEqual的函数进行测试):
expectEqual((*pkgname.StructName)(nil), actualValue)

注意,(*pkgname.StructName)(nil)是一种类型转换,它将nil(指针)值转换为*pkgname.StructName指针类型。

参考相关问题:

https://stackoverflow.com/questions/30162256/convert-nil-interface-to-pointer-of-something-in-golang/30162432#30162432

https://stackoverflow.com/questions/29138591/hiding-nil-values-understanding-why-golang-fails-here/29138676#29138676

英文:

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:

https://stackoverflow.com/questions/30162256/convert-nil-interface-to-pointer-of-something-in-golang/30162432#30162432

https://stackoverflow.com/questions/29138591/hiding-nil-values-understanding-why-golang-fails-here/29138676#29138676

huangapple
  • 本文由 发表于 2022年1月13日 13:51:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/70692007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定