Skip to content

Commit 7446935

Browse files
committed
Added type parameters module along with generics
1 parent cd09dfd commit 7446935

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

go_basics/go.work

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@ use (
1515
./reader
1616
./structs
1717
./typeConversionsAndInferrence
18+
./typeParametersAndGenerics
1819
./variables
1920
)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module anarchymonkey.com/go-basics/typeParametersAndGenerics
2+
3+
go 1.20
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func printValues[T comparable](values []T) {
6+
fmt.Println("The values are", values)
7+
}
8+
9+
type DataParser[T any, I int] struct {
10+
Data []T
11+
12+
Name string
13+
14+
Id I
15+
}
16+
17+
func main() {
18+
19+
fmt.Println("learning about type Parameters")
20+
21+
s := []string{
22+
"Aniket",
23+
"Amitava",
24+
"Tula",
25+
}
26+
27+
nums := []int{
28+
1, 2, 3, 4, 5,
29+
}
30+
31+
printValues(s)
32+
printValues(nums)
33+
34+
// generics
35+
36+
var parsedData DataParser[string, int] = DataParser[string, int]{
37+
Data: s,
38+
Name: "Aniket",
39+
Id: 1,
40+
}
41+
42+
fmt.Printf("The data is %v & the name to which it belongs to is %s, the id is %d", parsedData.Data, parsedData.Name, parsedData.Id)
43+
44+
}

0 commit comments

Comments
 (0)