Skip to content

Commit 89f885f

Browse files
committed
generics passing slices and comparing values with comparable
1 parent 1e2cccb commit 89f885f

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Diff for: generics/main.go

+19
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,17 @@ func printThis[T any](value T) {
77
fmt.Println(value)
88
}
99

10+
// index returns the index in the slice for the given item
11+
// we need to use `comparable` in order to be able to compare values
12+
func index[T comparable](vs []T, t T) int {
13+
for i, v := range vs {
14+
if v == t {
15+
return i
16+
}
17+
}
18+
return -1
19+
}
20+
1021
// getKeys returns the keys of the map
1122
// The value type doesn’t have any restraints but the key type should always
1223
// satisfy the comparable constraint.
@@ -30,4 +41,12 @@ func main() {
3041

3142
keysInt := getKeys(map[int]int{1: 1, 2: 2})
3243
fmt.Println(keysInt)
44+
45+
46+
arrStr := []string{"one", "two", "three"}
47+
arrInt := []int{1, 3, 2}
48+
idxStr := index(arrStr, "three")
49+
idxInt := index(arrInt, 3)
50+
fmt.Println(idxStr)
51+
fmt.Println(idxInt)
3352
}

0 commit comments

Comments
 (0)