Struct and Method in Golang


You learned about data type and variable in Golang. So, you can declare a lot of variable in Golang program. But, the helpful thing in Golang is You can group many variable in a form and We can call it “struct”. “Struct” in Golang is collection of fields data. If you knew about Object Oriented Programming, it seem a “class” of object in real life.

I call each student is a object, and declare a “struct” call student. This struct contain 2 fields name(string) and age(integer).

Example, I want to code a simple program, it store a list students in class. Each student has name and age. And I want to print all of them on screen.

This student struct type has name and age fields.

Now, I have a form struct for student with 2 field

Next, I will declare object student from struct by create a variable objectStudent1 with init data for struct

You can access field in struct by using “.”

An & prefix yields a pointer to the struct. You can also use dots with struct pointers – the pointers are automatically dereferenced.

package main
import "fmt"

type student struct {
    name string
    age  int

func main() {
    objectStudent1 := student{name: "Student 1", age: 16}

    objectStudent2 := student{name: "Student 2", age: 22}

    fmt.Println("Student 1",  objectStudent1)
    fmt.Println("Student 1",  objectStudent1)

   fmt.Println("name of Student 1",

    objectStudent2.age = 23
    fmt.Println("age of Student 2", objectStudent1.age)

    pointerStudent1 := &objectStudent1


Struct has support method. That is a function and owner by declared struct

Continue with our example

I want to declare 3 func(method) for struct student

  1. PrintOutNameAndAge
  2. IncreaseAge
  3. GetName

func(stu student) PrintOutNameAndAge() {
    fmt.Println("Name", name)
    fmt.Println("Age", age)

func(stu *student) IncreaseAge(i int) {
    stu.age = stu.age + i

function(stu student) GetName() string {

Now, in main function, we try call them on objectStudent1 by using “.”

Go automatically handles conversion between values and pointers for method calls. You may want to use a pointer receiver type to avoid copying on method calls or to allow the method to mutate the receiving struct.




Next we’ll look at Go’s mechanism for grouping and naming related sets of methods: interfaces.

View on github


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s