Skip to content

Commit bda2313

Browse files
committed
generics
1 parent 7a383dd commit bda2313

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

generics/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module generics
2+
3+
go 1.20

generics/main.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"fmt"
7+
)
8+
9+
type Person struct {
10+
Name string `json:"name"`
11+
Age uint `json:"age"`
12+
}
13+
14+
type Employee struct {
15+
Person
16+
Company string `json:"company"`
17+
}
18+
19+
// parseJson can accept body of type string but can return pointer to "any" type data
20+
// because of T used as generics here
21+
func parseJson[T any](body string) *T {
22+
s := new(T)
23+
24+
decoder := json.NewDecoder(bytes.NewBufferString(body))
25+
26+
if err := decoder.Decode(s); err != nil {
27+
panic(err)
28+
} else {
29+
return s
30+
}
31+
}
32+
33+
const (
34+
jsonString = `{"name": "Gurkirat Singh", "age": 21, "company": "Turing"}`
35+
)
36+
37+
func main() {
38+
// type specified in the [ and ] will be replaced as the type in the function
39+
// on hover you will see it returns *Person
40+
person := parseJson[Person](jsonString)
41+
42+
// here, on hover you will see it returns *Employee
43+
employee := parseJson[Employee](jsonString)
44+
45+
fmt.Printf("%+v\n", person)
46+
fmt.Printf("%+v\n", employee)
47+
48+
}

go.work

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use (
44
./datatypes
55
./deferfunc
66
./funcname
7+
./generics
78
./helloworld
89
./panic
910
./polymorphism

0 commit comments

Comments
 (0)