golang 方法 如何设置默认值
在go语言中,可以使用函数参数的默认值来达到设置默认值的目的。
例如:
func hello(name string, greeting string) {
if len(greeting) == 0 {
greeting = \"Hello\"
}
fmt.Printf(\"%s, %s!\\n\", greeting, name)
}
func main() {
hello(\"John\", \"Hi\")
hello(\"Smith\", \"\") // It will print \"Hello, Smith!\"
}
在上述代码中,以 greeting
参数为例,可以通过条件判断来判断参数是否为空,如果为空则使用默认值。
还有一种常见的写法是使用可变参数,如下所示:
func hello(name string, args ...string) {
greeting := \"Hello\"
if len(args) > 0 {
greeting = args[0]
}
fmt.Printf(\"%s, %s!\\n\", greeting, name)
}
func main() {
hello(\"John\", \"Hi\")
hello(\"Smith\") // It will print \"Hello, Smith!\"
}
在上述代码中,使用了可变参数 args
来作为函数的参数,当传入的参数数量为 1 时,即为 greeting
参数,如果没有传入参数,则使用默认值。