File tree Expand file tree Collapse file tree 3 files changed +52
-0
lines changed Expand file tree Collapse file tree 3 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ module generics
2+
3+ go 1.20
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 44./datatypes
55./deferfunc
66./funcname
7+ ./generics
78./helloworld
89./panic
910./polymorphism
You can’t perform that action at this time.
0 commit comments