|
3 | 3 | // Definition |
4 | 4 | // ------------------------------------ |
5 | 5 |
|
6 | | -// TODO |
| 6 | +func functionName([parameters]) [returnType] { |
| 7 | + // ... |
| 8 | +} |
7 | 9 |
|
8 | 10 | // ------------------------------------ |
9 | 11 | // Declaration Example |
10 | 12 | // ------------------------------------ |
11 | 13 |
|
12 | | -// TODO |
| 14 | +func myFunction(x float32) { |
| 15 | + // ... |
| 16 | +} |
| 17 | + |
| 18 | +func getNumber() float32 { |
| 19 | + return 10.5 |
| 20 | +} |
| 21 | + |
| 22 | +func add(first int, second int) int { |
| 23 | + return first + second |
| 24 | +} |
| 25 | + |
| 26 | +func swap(first string, second string) (string, string) { |
| 27 | + return second, first |
| 28 | +} |
13 | 29 |
|
14 | 30 | // ------------------------------------ |
15 | 31 | // Named Parameters (Keyword Arguments) |
16 | 32 | // ------------------------------------ |
17 | 33 |
|
18 | | -// TODO |
| 34 | +// No Native Support. |
| 35 | +// Use structs when argument names matter. |
| 36 | + |
| 37 | +type CreateUserOptions struct { |
| 38 | + Name string |
| 39 | + Age int |
| 40 | +} |
| 41 | + |
| 42 | +func CreateUser(options CreateUserOptions) { |
| 43 | + // ... |
| 44 | +} |
19 | 45 |
|
20 | 46 |
|
21 | 47 | // ------------------------------------ |
22 | 48 | // Optional Parameters |
23 | 49 | // ------------------------------------ |
24 | 50 |
|
25 | | -// TODO |
| 51 | +// No Native Support. |
| 52 | +// Use zero values, structs, or separate functions. |
26 | 53 |
|
27 | 54 |
|
28 | 55 | // ------------------------------------ |
29 | 56 | // Default Argument for Parameters |
30 | 57 | // ------------------------------------ |
31 | 58 |
|
32 | | -// TODO |
| 59 | +// No Native Support. |
| 60 | +// Assign defaults inside the function when needed. |
33 | 61 |
|
34 | 62 |
|
35 | 63 | // ------------------------------------ |
36 | 64 | // Variable Number of Arguments to a Function Parameters |
37 | 65 | // ------------------------------------ |
38 | 66 |
|
39 | | -// TODO |
| 67 | +func addAll(numbers ...int) int { |
| 68 | + result := 0 |
| 69 | + |
| 70 | + for _, number := range numbers { |
| 71 | + result += number |
| 72 | + } |
| 73 | + |
| 74 | + return result |
| 75 | +} |
| 76 | + |
| 77 | +addAll(1, 2, 3) |
40 | 78 | ``` |
41 | 79 |
|
42 | 80 | ```Go |
43 | 81 | // ------------------------------------ |
44 | 82 | // Generic/Template |
45 | 83 | // ------------------------------------ |
46 | 84 |
|
47 | | -// TODO |
| 85 | +// Since Go 1.18 |
| 86 | +func Identity[T any](value T) T { |
| 87 | + return value |
| 88 | +} |
| 89 | + |
| 90 | +func Contains[T comparable](values []T, target T) bool { |
| 91 | + for _, value := range values { |
| 92 | + if value == target { |
| 93 | + return true |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + return false |
| 98 | +} |
48 | 99 | ``` |
49 | 100 |
|
50 | 101 | ```Go |
|
0 commit comments