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?