Avatar ·

如何在Go中实现可选函数参数?其他语言重载的替代方案

大家好!我从Python和Java转到Go,遇到了一个问题。在那些语言中,我习惯了函数重载和可选参数,可以设置默认值。例如,在Python中我会这样写: ```python def create_user(name, age=None, city="Moscow"): ... ``` 而在Go中,我不能直接省略参数或编写两个同名函数。我需要创建一个用户注册函数,其中只有`name`是必需的,而`age`和`city`是可选的。 我尝试了这样的代码,但编译器报错: ```go func CreateUser(name string, age int, city string) { // 如果未传递age,我希望它为0 // 如果未传递city,我希望为"Moscow" } func CreateUser(name string) { // 错误:CreateUser redeclared CreateUser(name, 0, "Moscow") } ``` 我查阅了文档——Go中没有函数重载。我见过使用指针的变通方法,但这样调用代码变得冗长:`CreateUser("Alex", nil, nil)`。有没有更好的方式?