登录
首页 >  Golang >  Go问答

将函数传递给辅助方法

来源:stackoverflow

时间:2024-04-26 12:18:35 295浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《将函数传递给辅助方法》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

go 中是否可以迭代一组函数?

我的单元测试文件中有这个辅助方法:

func helper(t *testing.t, f func(string) bool, stringarray []string, expected bool) {
    for _, input := range stringarray {
        if f(input) != expected {
            t.errorf("expected '%v' for string: %v", !expected, input)
        }

    }
}

而不是像这样丑陋地复制/粘贴一行并更改第二个参数:

func test_isunique(t *testing.t) {
    var valid = []string{"", "b", "ab", "acd", "asdfjkl", "aa"}
    var invalid = []string{"aa", "avva", "aaa", "asdfweryhfda", "asdfjkal"}
    helper(t, funca, valid, true)
    helper(t, funcb, invalid, false)
    helper(t, funcc, valid, true)
    helper(t, funcd, invalid, false)
    helper(t, funce, valid, true)
    helper(t, funcf, invalid, false)
    helper(t, funcg, valid, true)
    helper(t, funch, invalid, false)
}

我想知道这里是否有一个 for 选项可以将其减少为 4 行主体函数

for f in [funcA, funcB, funcB, funcC, funcD, etc]: // Fix this
    helper(t, f, valid, true)
    helper(t, f, invalid, false)

请原谅上面 python/go 的混合:)


解决方案


是的,这是可能的。例如。您可以覆盖任何切片,包括元素类型为函数类型的切片。只需将您的函数放入切片中即可:

fs := []func(string) bool{funca, funcb, funcc, funcd, ...}

for _, f := range fs {
    helper(t, f, valid, true)
    helper(t, f, invalid, false)
}

对于您想要实现的目标,表驱动测试可能更合适。请检查 Go Wiki: Table Driven TestsThe Go Blog: Using Subtests and Sub-benchmarks

惯用的方法是使用表驱动测试:

func testmyfunction(t *testing.t) {
  valid := []string{"", "b", "ab", "acd", "asdfjkl", "aa"}
  cases := []struct{
    name string,
    f func(string) bool
    input []string
    expected bool
  }{
    {
       "test func a",
       funca,
       valid,
       true
    },
    // other test cases
  }

  for _, tc := range cases {
      t.run(tc.name, func(t *testing.t) {
          helper(t, tc.func, tc.input, tc.expected)
      })
  }
}

附带说明:您实际上可以使用 Helper 函数显式标记辅助函数。这可以确保您的辅助函数从运行测试时打印的行信息中排除:

func helper(t *testing.T) {
  t.Helper()
  // Helper function code
}

今天关于《将函数传递给辅助方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>