有没有办法在Go的函数中指定默认值?我试图在文档中找到这个,但我找不到任何指定这甚至可能的东西.
func SaySomething(i string = "Hello")(string){
...
}
Run Code Online (Sandbox Code Playgroud)
小智 81
不,但还有一些其他选项可以实现默认值.关于这个主题有一些很好的博客文章,但这里有一些具体的例子.
选项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)
}
Run Code Online (Sandbox Code Playgroud)
选项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)
}
Run Code Online (Sandbox Code Playgroud)
选项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)
}
Run Code Online (Sandbox Code Playgroud)
选项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)
}
Run Code Online (Sandbox Code Playgroud)
sda*_*zig 47
不,谷歌的权力选择不支持.
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ
不,没有办法指定默认值。我相信这样做的目的是为了提高可读性,但要花更多的时间(并且希望是在作者端)花些时间。
我认为拥有“默认”的正确方法是拥有一个新功能,该功能将默认提供给更通用的功能。有了这个,您的代码就变得更加清晰了。例如:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
Run Code Online (Sandbox Code Playgroud)
花费很少的精力,我做了一个做普通事情的函数并重用了通用函数。您可以在许多库中看到这一点,fmt.Println例如,只需在其他情况下添加换行符即可fmt.Print。但是,在阅读某人的代码时,很明显他们通过调用的函数打算做什么。使用默认值时,如果不使用函数来引用默认值的实际含义,我将不知道会发生什么。