英文:
Assertion in non-test function in Go
问题
我想在一个函数中使用断言,但它不是一个测试函数,只是一个普通的函数。我想使用类似 assert.Equal(param1, some_constant)
的语法。我找到了这个包:https://godoc.org/github.com/stretchr/testify/assert
不过,它似乎也需要 testing
包,并且需要给函数传递一个类型为 *testing.T
的参数。在Go语言中是否有其他的断言函数,可以直接调用 assert
函数,而不依赖于任何其他的测试包或参数?
英文:
I want to use assertion in a function, but it is not a test function. It is just a normal function, and I want to use something like assert.Equal(param1, some_constant)
. I came across the following package: https://godoc.org/github.com/stretchr/testify/assert
Though, it appears that it also requires the testing
package, and to give to a function a parameter of type *testing.T
. Is there any other assert function in Go, where I can directly call the assert
function without actually relying on any other testing package or parameter?
答案1
得分: 4
Go语言不提供断言(assertions)。Go团队在语言FAQ中有一个相关的部分,链接在这里:https://golang.org/doc/faq#assertions
如果你真的需要断言,你可以编写一个普通的函数,接受两个值,并根据它们是否相等来执行相应的操作。
英文:
Go does not provide assertions. There is a section in the language FAQ from the Go team here: https://golang.org/doc/faq#assertions
If you really into it, you can just write a normal function that accepts two values and does something if they evaluate to equal or not equal, as you desire.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论