有没有办法在Go的函数中指定默认值?我试图在文档中找到这个,但我找不到任何指定这甚至可能的东西。
func SaySomething(i string = "Hello")(string){
...
}
不,但还有一些其他选项可以实现默认值。关于这个问题有一些good blog posts,但这里有一些具体的例子。
选项1:调用者选择使用默认值
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
if a == "" {
a = "default-a"
}
if b == 0 {
b = 5
}
return fmt.Sprintf("%s%d", a, b)
}
选项2:最后一个可选参数
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
b := 5
if len(b_optional) > 0 {
b = b_optional[0]
}
return fmt.Sprintf("%s%d", a, b)
}
选项3:配置结构
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
A string `default:"default-a"` // this only works with strings
B string // default is 5
}
func Concat3(prm Parameters) string {
typ := reflect.TypeOf(prm)
if prm.A == "" {
f, _ := typ.FieldByName("A")
prm.A = f.Tag.Get("default")
}
if prm.B == 0 {
prm.B = 5
}
return fmt.Sprintf("%s%d", prm.A, prm.B)
}
选项4:完全可变参数解析(javascript样式)
func Concat4(args ...interface{}) string {
a := "default-a"
b := 5
for _, arg := range args {
switch t := arg.(type) {
case string:
a = t
case int:
b = t
default:
panic("Unknown argument")
}
}
return fmt.Sprintf("%s%d", a, b)
}
不,没有办法指定默认值。我相信这是为了提高可读性而完成的,代价是在作者的最后一点时间(并且,希望,想到)。
我认为拥有“默认”的正确方法是使用一个新函数,将该默认值提供给更通用的函数。有了这个,您的代码就会变得更加清晰。例如:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
通过很少的努力,我创建了一个功能,它可以执行常见功能并重用通用功能。您可以在许多库中看到这一点,例如fmt.Println
只是为fmt.Print
添加换行符。但是,在阅读某人的代码时,很明显他们打算通过他们调用的函数来做什么。使用默认值,我不知道应该发生什么,如果没有使用函数来引用默认值实际是什么。