Go中函数重载的替代方法?

Cod*_*der 12 overloading go

是否可以像使用Golang的C#中的函数重载或可选参数一样工作?或者可能是另一种方式?

joh*_*ohn 9

Go中可选参数的惯用答案是包装函数:

func do(a, b, c int) {
    // ...
}

func doSimply(a, b) {
    do(a, b, 42)
}
Run Code Online (Sandbox Code Playgroud)

故意遗漏了函数重载,因为它使代码难以阅读.

  • *因为它使代码难以阅读.*这完全是主观的.我不这么认为,并非总是如此. (4认同)

Pao*_*lla 8

直接支持函数重载和可选参数.你可以解决它们构建自己的参数struct.我的意思是这样的(未经测试,可能无效......)编辑:现在测试...

package main

    import "fmt"

    func main() {
        args:=NewMyArgs("a","b") // filename is by default "c"
        args.SetFileName("k")

        ret := Compresser(args)
        fmt.Println(ret)
    }

    func Compresser(args *MyArgs) string {
        return args.dstFilePath + args.srcFilePath + args.fileName 
    }

    // a struct with your arguments
    type MyArgs struct 
    {
        dstFilePath, srcFilePath, fileName string 
    }

   // a "constructor" func that gives default values to args 
    func NewMyArgs(dstFilePath string, srcFilePath string) *MyArgs {
        return &MyArgs{
              dstFilePath: dstFilePath, 
              srcFilePath:srcFilePath, 
              fileName :"c"}
    }

    func (a *MyArgs) SetFileName(value string){
      a.fileName=value;
    }
Run Code Online (Sandbox Code Playgroud)