在Go中的非测试函数中的断言

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

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.

huangapple
  • 本文由 发表于 2017年8月15日 05:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/45683134.html
匿名

发表评论

匿名网友

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

确定