Go Class

Go does not have a keyword class. But it does not limit us to define a class in Go. We can define a class in a way which is similar to defining variables; and define methods of a class, by providing set of methods on the common type.

For example, we can define a class by defining a struct and implement methods on the struct type. And this struct will be analogous to a class concept.

Example

In the following example, we will define a class in golang using Go structures.

example.go

package main

import "fmt"

// struct definition
type Student struct {
   name string
   rollNumber int
}

// associate method to Strudent struct type
func (s Student) PrintDetails() {
	fmt.Println("Student Details\n---------------")
	fmt.Println("Name :", s.name)
	fmt.Println("Roll Number :", s.rollNumber)
}

func main() {
	var stud1 = Student{name:"Anu", rollNumber:14} 
	stud1.PrintDetails()
}

Output

Student Details
---------------
Name : Anu
Roll Number : 14

The Student struct is analogous to a class below provided in pseudo code.

Pseudo Code

class Student{
    name
    rollnumber
    
    function PrintDetails(){
        // print details using this.name, this.rollnumber
    }

}
ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to word around a Class concept is in Go, with the help of examples.