-1

I just started learning Golang today. So, I suppose this question is a basic one howerver I tried what I can try, but get error.

So, I have defined a Student struct type:

type Student struct {
    firstname string    `json:"first_name"`
    id   int `json:"id"`
}

I want to have a map data structure, in which the map's key represent "class id" & the value of each key in this map is an array of Student. This is what I have tried:

var studentsMap = make(map[int][]Student)

func registerStudent(classId int, studentName string, studentId int) {
   var studentsInClass = studentsMap[classId]
   if studentsInClass == nil {
       studentsInClass = []Student{}
   }

   // append the new student to the studentsInClass array   
   var updatedStudentsArr = append(studentsInClass, Student{studentName, studentId})

   // update the map for this class id with updated array of students
   // Compiler ERROR: Cannot use 'updatedStudentsArr' (type []Student) as the type Student
   studentsMap[classId] = updatedStudentsArr
}

As you see in my comment in the code, when I try to update the studentsMap with the new array, I get compiler error Cannot use 'updatedStudentsArr' (type []Student) as the type Student. Why is that? My guess is that I defined wrongly the studentsMap map type, but how to fix?

user842225
  • 5,445
  • 15
  • 69
  • 119
  • 2
    Unrelated: Export your fields if you want to JSON a Student. – Volker Sep 13 '22 at 20:32
  • 1
    The playground code is [here](https://go.dev/play/p/744Z7e6wtgs). This is working, – nipuna Sep 13 '22 at 20:33
  • @Volker Thanks! For sure I am doing some stupid stuff as it was my day-1 of Go language (Day 2 now). Could you please provide a link or ref or code snippet of how-to regarding to your comment of "Export your field"? – user842225 Sep 14 '22 at 08:23

1 Answers1

0

The code you posted seems to be working fine, as pointed out by @nipuna in the comments.

As a small note, when you test for a key,value existence in go you get two values, the latter being a boolean. You can thus use the following to test whether studentsMap[classId] exists

studentsInClass, ok := studentsMap[classId]
if !ok {
    studentsInClass = []Student{}
}

Regarding your second question related to @Volker's comment, you can read more about exporting struct fields in the following answers.

If you are using an IDE, it might be warning you about it (e.g. in VSCode I get struct field firstname has json tag but is not exported).

https://stackoverflow.com/a/50320595/5621318

https://stackoverflow.com/a/11129474/5621318

https://stackoverflow.com/a/25595269/5621318

el_gio
  • 56
  • 7