gooverloading

Alternative for function overloading in Go?


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


Solution

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