4 j3 D! a; O. J. \" I9 W解决方案: 2 e& M/ R! `' R 不,但还有一些其他选项可以实现默认值。有一些关于这个主题的好博客文章,但这里有一些具体的例子。; m, ]2 E M2 l: `& r' s 选项 1: 调用方选择使用默认值 . g3 H- f/ G; [7 b4 R
// 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)} {' O: U q b8 U# E) V
选项 2: 末尾单个可选参数 5 K* K1 X1 Z; D: v
// 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 return fmt.Sprintf("%s%d",a,b)} . s1 ?* P3 c- _$ T/ F
选项 3: 配置结构5 c- f8 D! j4 _
// 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)}( S1 w; N0 J3 }! n
选项 4: 全可变参数分析(javascript 风格) / \; M) j% t( \4 {1 z
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)} $ D1 ~; p* ~3 n6 B% _+ O2 h/ E