-
Notifications
You must be signed in to change notification settings - Fork 41
/
empty.go
96 lines (79 loc) · 1.28 KB
/
empty.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import "fmt"
func main() {
var i any
// go < 1.18
// var i interface{}
i = 7
fmt.Println(i)
i = "hi"
fmt.Println(i)
// Rule of thumb: Don't use any :)
s := i.(string) // type assertion
fmt.Println("s:", s)
/*
n := i.(int) // will panic
fmt.Println("n:", n)
*/
// comma, ok
n, ok := i.(int)
if ok {
fmt.Println("n:", n)
} else {
fmt.Println("not an int")
}
switch i.(type) { // type switch
case int:
fmt.Println("an int")
case string:
fmt.Println("a string")
default:
fmt.Printf("unknown type: %T\n", i)
}
/*
fmt.Println(maxInts([]int{3, 1, 2}))
fmt.Println(maxFloat64s([]float64{3, 1, 2}))
*/
fmt.Println(max([]int{3, 1, 2}))
fmt.Println(max([]float64{3, 1, 2}))
}
type Number interface {
int | float64
}
// func max[T int | float64](nums []T) T {
func max[T Number](nums []T) T {
if len(nums) == 0 {
return 0
}
max := nums[0]
for _, n := range nums[1:] {
if n > max {
max = n
}
}
return max
}
func maxInts(nums []int) int {
if len(nums) == 0 {
return 0
}
max := nums[0]
for _, n := range nums[1:] {
if n > max {
max = n
}
}
return max
}
func maxFloat64s(nums []float64) float64 {
if len(nums) == 0 {
return 0
}
max := nums[0]
for _, n := range nums[1:] {
if n > max {
max = n
}
}
return max
}