Go的函数重载的替代方法? [英] Alternative for function overloading in Go?

查看:137
本文介绍了Go的函数重载的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

直接支持函数重载和可选参数。你可以在他们周围建立你自己的参数struct。我的意思是这样(未经测试,可能无法正常工作...)编辑:现在测试...

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

这篇关于Go的函数重载的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆