Alternative for function overloading in Go?

后端 未结 4 1546
不知归路
不知归路 2021-02-19 16:14

Is it possible to work similar way like the function overloading or optional parameter in C# using Golang? Or maybe an alternative way?

4条回答
  •  终归单人心
    2021-02-19 16:55

    Neither function overloading nor optional arguments are directly supported. You could work around them building your own arguments struct. I mean like this (untested, may not work...) EDIT: now tested...

    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;
        }
    

提交回复
热议问题