Defining the Student Structure
We begin by defining a structure named Student. The Student struct contains two fields:- name: a string representing the student’s name.
- grades: a slice of integers representing the student’s scores.
- displayName: A method with a pointer receiver that prints the student’s name.
- calculatePercentage: This method calculates the student’s average grade by summing all grades and dividing the sum by the total number of grades. Although it is described as calculating a percentage, the computation returns the average score.
Understanding method sets is vital for delving into interfaces in Go, as they are built on these underlying concepts.
Using the Student Methods in the Main Function
In the next code snippet, we initialize a Student instance with the name “Joe” and a slice containing three grades: 90, 75, and 80. We then call the displayName method to print the student’s name and use the calculatePercentage method to compute and print the average grade with two decimal points of precision.Try modifying the Student struct and its methods to handle more complex calculations or additional student attributes. Experiment with other data types and see how method sets interface with Go’s overall type system.