Structures and Methods in Go

In this post I am going to discuss Go lang’s another features, structs

As I told earlier that Go is not a typical Object Oriented Language. Structures is kind of answers of what you do with Classes and objects. Well, Structure is not a special concept to Go only. If you have worked on C language then you could have an idea what is it all about.

Let’s write a simple program

package main

import "fmt"

type person struct {
	name   string
	age    int
	height float64
	weight float64
}

func (p person) get_info() {
	fmt.Println("Name:- " + p.name)
	fmt.Println("Age:- ", p.age,"years ")
	fmt.Println("Height:- ", p.height,"cm")
	fmt.Println("Weight:- ", p.weight,"KG")
}

func main() {
	me := person{name: "Umar", age: 29, height: 1.6, weight: 68}
	me.get_info()
}

Ok this is the complete program. After typical declarations I am defining a struct with name person. As you remember you write variable name first and then it’s type in Go.

Alright.. so now we have to use this struct. For that I am going to create a method, method telling what action can be performed with this struct. So here I made a method name get_info(). This method is similar to class methods or member methods in OOP. To connect get_info with the struct Person you pass the method type,  in our case it is Person. You need something to refer that structure so p is a variable that will be used to access the Person structure. If you are a PHP programmer, it provides using facility to pass methods to anonymous functions. It is not the EXACT thing but giving you an idea that is the same way you pass an outer variable within a scope.

Alright so now get into main()

me := person{name: "Umar", age: 29, height: 1.6, weight: 68}

The line above is kind of a constructor of a class. If Person was a class you were going to pass values like:

person = new Person('Umar',29,1.6,68)

then you call the method. The output will be something like below:

Name:- Umar
Age:- 38 years
Height:- 1.6 cm
Weight:- 68 KG

You can also change individual structure member.. for instance:

p.name = Ali

That’s it for now. In new post of Go series I will be discussing other features of Golang. Stay tuned!

 

 

If you like this post then you should subscribe to my blog for future updates.

* indicates required