I am doing a Grading Software for Practice. I am saving the Grades to a Json file and I want to try and use Generics to reduce the amount of code. I am fairly knew at Go and will programming overall.
Here is the json
{
“homework”: [
{
“Name”: “Homework1”,
“Grade”: 45
},
{
“Name”: “Homework2”,
“Grade”: 45
}
],
“lab”: [
{
“Name”: “Lab1”,
“Grade”: 12
},
{
“Name”: “Lab2”,
“Grade”: 45
}
]
}
My idea is something below but I know Go doesnt support macro substitutions
Here are the structs
type Subject struct {
Homework []Homework json:"homework"
Lab []Lab json:"lab"
//Weight []Weight
}
type Homework struct {
Name string
Grade int
}
type Lab struct {
Name string
Grade int
}
Function is below
//Instead of using category2.Homework would want something like category2.result
//this way I can use the same code for all of the similar structs
func displayT Grades {
var result []T
//var cat map[string]any
content, err := ioutil.ReadFile(“grades.json”)
if err != nil {
log.Fatal(err)
}
category2 := Subject{}
err = json.Unmarshal(content, &category2)
fmt.Println(category2)
res := category2
fmt.Println(res)
for key, value := range category2.Homework {
fmt.Println(key, value)
}
if err != nil {
log.Fatal(err)
}
}