Avatar ·

如何在Go中实现可选函数参数?(类似重载)

大家好!我刚刚从Java和Python转到Go,遇到了一个让我非常困惑的问题。 在我之前熟悉的语言中,可以轻松声明带有可选参数的函数。例如,在Python中我可以这样写:def connect(host, port=8080, timeout=30)。然后可以这样调用:connect("localhost")、connect("localhost", 9090) 或 connect("localhost", 9090, 60)。 现在我尝试在Go中做同样的事情。我需要编写一个连接服务器的函数,其中port和timeout应该是可选的。我尝试了直观的方法: ```go func connect(host string, port int = 8080, timeout int = 30) { // ... 连接代码 } ``` 但编译器报错:"syntax error: unexpected =, expecting {"。原来Go不支持参数的默认值。 我还了解到Go没有函数重载(overloading)。也就是说,我不能像在Java中那样简单地创建两个参数数量不同的函数版本: ```go