default values
# Node.js
function greet(name = "stranger") {
return `hello ${name}`;
}
let message = greet();
console.log(message);
message = greet("bob");
console.log(message);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Output
hello stranger
hello bob
1
2
2
# Go
use pointers and check for nil to know if explicitly left blank
package main
import "fmt"
func greet(name *string) string {
n := "stranger"
if name != nil {
n = *name
}
return fmt.Sprintf("hello %s", n)
}
func main() {
message := greet(nil)
fmt.Println(message)
name := "bob"
message = greet(&name)
fmt.Println(message)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output
hello stranger
hello bob
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22