英文:
Testing Functions with the same name in GO
问题
在Go语言中,可以编写特定于结构体的函数。
type one struct{}
func (o *one) fly() {}
我的问题是,如果有两个函数具有相同的名称但指向不同的结构体,该如何测试函数。
type one struct{}
func (o *one) fly() {}
type two struct{}
func (t *two) fly() {}
由于Go测试的格式是TestXxx(t *testing.T)
,我不确定如何能够分别测试每个函数。
谢谢。
英文:
In go it is possible to write functions that are specific to structs.
type one struct{}
func (o *one) fly() {}
My questions is how can you test a function if there are two functions with the same name but point to different structs.
type one struct{}
func (o *one) fly() {}
type two struct{}
func (t *two) fly() {}
Since the formatting for GO tests is TestXxx (t *testing.T) {}
I'm unsure how I would be able to test each function separately.
Thanks
答案1
得分: 7
TestXxx
只是一种命名约定。Xxx
可以是任何你想要的内容,但是Test
(以及Benchmark
和Example
)是必需的。所以,声明两个测试函数——TestOneFly
和TestTwoFly
,就这样。或者你可以在一个测试中测试两个,初始化两个结构体。
英文:
TestXxx
is just a naming convention. Xxx
may be anything you want, but Test
(with Benchmark
and Example
) are required. So, declare 2 testing functions — TestOneFly
and TestTwoFly
, that's all. Or you can test both in TestFly
, initializing both structs in one test.
答案2
得分: 0
使用点运算符在结构体实例上调用特定的函数。
aOne := one{}
aOne.fly() //调用第一个版本
aTwo := two{}
aTwo.fly() //调用第二个版本
英文:
Invoke the specific function using the dot operator on an instance of the struct.
aOne := one{}
aOne.fly() //Calls the first version
aTwo := two{}
aTwo.fly() //Calls the second version
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论