代码之家  ›  专栏  ›  技术社区  ›  Matias Barrios

golang中as参数的函数数组

  •  0
  • Matias Barrios  · 技术社区  · 7 年前

    如何将函数数组传递给主函数validate? 我找不到正确的语法

    package main
    
    import (
        "fmt"
    )
    
    func upper(input string) string {
    
        return "hola"
    }
    
    func Validate(spec string, validations []func(string) string) {
    
        for err, exec := range validations {
            fmt.Println(exec(spec))
        }
    }
    
    
    
    func main() {
        Validate("Hola", []func{upper})
    }
    

    当做!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sergey Donskoy    7 年前

    下面是使用slice参数的正确示例。在使用slice literal之前,需要指定它的类型。

    package main
    
    import (
        "fmt"
    )
    
    func upper(input string) string {
    
        return "hola"
    }
    
    func Validate(spec string, validations []func(string) string) {
    
        for err, exec := range validations {
            fmt.Println(exec(spec))
        }
    }
    
    func main() {
        Validate("Hola", []func(string) string{upper})
    }