skip to content
Alvin Lucillo

Using pointer in Go receiver func

/ 1 min read

💻 Tech

In Go, if you want to modify a struct’s value inside a receiver function, you need to pass a pointer to the receiver function. For example:

type School struct {
    StudentList StudentList
}

func (s *School) AddStudent(student Student) {
    s.StudentList = append(s.StudentList, student)
}

If you don’t pass a pointer to the receiver function, the value of the struct will not be modified. Passing a pointer to the receiver function is helpful when there are different parts of the code that need to modify the same struct.