不,但还有一些其他选项可以实现默认值。关于这个主题有一些很好的博客文章,但这里有一些具体的例子。
选项 1: 调用方选择使用默认值
// Both parameters are optional, use empty string for default valuefunc Concat1(a string, b int) string { if a == "" { a = "default-a" } if b == 0 { b = 5 } return fmt.Sprintf("%s%d", a, b)}
// 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 defaultstype 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)}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)