Provide Best Programming Tutorials

How to define the struct in Golang

The struct in Golang is like the class in Java, define struct is very easy and simple, let me show you an example, let’s say we have struct called Student :

type Student struct {
	name   string
	gender string
	age    int
	id     int
	score  float64

the type and struct are keywords in Golang, Student is the name of the struct we created.

This Student struct has 5 attributes which are name, gender, age, id, score.

Next, let’s create methods for the Student struct.

Be careful we shouldn’t define methods inside struct but should outside it.

Let’s say the Student has a method called haveClass , then we should define it like this:

func (stu *Sutdent) haveClass(){
  println("The student is having class...")

The key point is here: func (stu *Sutdent) haveClass()

Bold black text indicates that this method is an instance method that belongs to the Student class.

That’s how we define a struct in Golang, I hope you like this article~

Leave a Reply

Close Menu