Methods in Golang

Methods in Golang  are like functions but with one key difference: they have a receiver argument , which gives access to the properties of the receiver . The receiver can be a struct or a non-struct type, but both must be in the same package. Methods cannot be created for types defined in other packages, including built-in types like int or string ; otherwise, the compiler will throw an error.

Methods in Golang

For example:

package main

import "fmt"

// Định nghĩa một struct
type person struct {
    name string
    age  int
}

// Định nghĩa một phương thức với struct receiver
func (p person) display() {
    fmt.Println("Name:", p.name)
    fmt.Println("Age:", p.age)
}

func main() {
    // Tạo một phiên bản của struct
    a := person{name: "a", age: 25}
    
    // Gọi phương thức
    a.display()
}

Result:

Name: a
Age: 25

Syntax

func(receiver_name Type)  method_name(parameter_list) (return_type) { 
// Code
}

Receiver: Can be accessed using this method.

Method with Receiver of struct type

In Go, you can define a method where the receiver is of type struct. The receiver is accessible inside the method. The previous example illustrates this approach with Receiver of type struct.

Method with Receiver is not struct type

Go also allows methods with non-struct receivers, as long as the receiver type and the method definition are in the same package. You cannot define a method with a receiver type from another package (e.g. int, string).

For example:

package main

import "fmt"

// Tạo một kiểu tùy biến dựa trên int
type number int

// Định nghĩa một phương thức với receiver không phải struct
func (n number) square() number {
    return n * n
}

func main() {
    a := number(4)
    b := a.square()

    fmt.Println("Square of", a, "is", b)
}

Result:

Square of 4 is 16

Method with receiver pointer

In Go, methods can have pointer receivers. This allows changes made in the method to be reflected in the caller, which is not possible with value receivers.

Syntax:

func (p *Type) method_name(...Type) Type {    // Code}

For example:

package main

import "fmt"

// Defining a struct
type person struct {
    name string
}

// Phương thức với receiver pointer để chỉnh sửa dữ liệu
func (p *person) changeName(newName string) {
    p.name = newName
}

func main() {
    a := person{name: "a"}
    
    fmt.Println("Before:", a.name)
    
    // Gọi phương thức này để thay đổi tên
    a.changeName("b")
    
    fmt.Println("After:", a.name)
}

Result:

Before: a
After: b

Method accepts both pointer and value

Unlike functions, Go methods can accept both value and pointer receivers. You can pass either a pointer or a value and the method will handle it accordingly.

For example:

package main
import "fmt"

type person struct {
    name string
}
// Phương thức với receiver pointer
func (p *person) updateName(newName string) {
    p.name = newName
}

// Phương thức với receiver value 
func (p person) showName() {
    fmt.Println("Name:", p.name)
}

func main() {
    a := person{name: "a"}
    
    // Gọi phương thức con trỏ cùng giá trị
    a.updateName("b")
    fmt.Println("After pointer method:", a.name)
    
    // Gọi phương thức giá trị với con trỏ
    (&a).showName()
}

Result:

After pointer method: b
Name: b

Difference between method and function

Method Jaw
Contains a receiver Does not contain receiver
It is possible to define methods with the same name but different types. Functions with the same name but different types are not allowed.
Cannot be used as a superlative Can be used as superordinate objects
Sign up and earn $1000 a day ⋙

Leave a Comment

5 Ways to Fix Apple Watch Not Pairing Error

5 Ways to Fix Apple Watch Not Pairing Error

While Apple Watch is a great way to track your daily fitness, send messages, and more, what happens if your Apple Watch won't pair?

The 6 Oldest Companies in the World Still Operating, Number 1 Has Been Operating for 1,400 Years

The 6 Oldest Companies in the World Still Operating, Number 1 Has Been Operating for 1,400 Years

What is the oldest company in the world? When was the oldest company in the world founded? Let's find out together!

How to review deleted notifications on Samsung

How to review deleted notifications on Samsung

In the new One UI 3.0 version on Samsung, users can use many other interesting and attractive features, such as reviewing deleted notifications on the Samsung status bar.

International Mens Day wishes, November 19 wishes for boyfriend, lover, husband sweet and romantic

International Mens Day wishes, November 19 wishes for boyfriend, lover, husband sweet and romantic

What are the best and shortest November 19 wishes for your lover? If you are out of ideas, this article will suggest meaningful November 19 wishes for you.

How to wear a sweater stylishly and comfortably

How to wear a sweater stylishly and comfortably

Basic sweaters are an indispensable part of all of our fall and winter wardrobes. Here are some simple yet fashionable ways to mix and match sweaters.

The easiest way to turn enemies into friends

The easiest way to turn enemies into friends

Having enemies is always an unpleasant situation. Luckily, you can turn your enemies into friends. Here are some simple ways to mend relationships that are available to everyone.

How many people can use one Netflix account at the same time?

How many people can use one Netflix account at the same time?

Since Netflix is ​​easily accessible on all devices including phones, tablets, game consoles, and streaming devices, you might be wondering how many people can watch Netflix at the same time on the same account.

Ways to center cells in a table on Word

Ways to center cells in a table on Word

Centering cells in Word when working with tables is an operation that needs to be performed to reformat the text in each cell according to regulations, as well as create a Word table with a more beautiful and easy-to-see layout.

Samsung partners with OpenAI to develop AI TV, promising many interesting features

Samsung partners with OpenAI to develop AI TV, promising many interesting features

Samsung Electronics is reportedly collaborating with OpenAI on an ambitious joint project to develop AI TVs that incorporate industry-leading artificial intelligence technologies.

Minecraft 1.21 update has an official release date

Minecraft 1.21 update has an official release date

After a lot of snapshots, additions, and changes, the update is complete and ready for release. The official Minecraft 1.21 release date has just been revealed!

Feast your eyes on the performance of Chinas skillfully dancing Robot

Feast your eyes on the performance of Chinas skillfully dancing Robot

In a stunning display of creativity, 16 humanoid robots from China's leading robotics company Unitree took the spotlight at CCTV's annual Spring Festival Gala.

Why are naturally dried clothes and machine dried clothes different?

Why are naturally dried clothes and machine dried clothes different?

Why are clothes and towels machine-dried soft and smooth, but when hung to dry they often feel scratchy or rough?

Why does NASA use a device with 36 pixels to monitor the universe?

Why does NASA use a device with 36 pixels to monitor the universe?

NASA's satellites use an imaging tool called Resolve, which has a sensor of just 36 pixels.

Cannot Connect to iTunes Store Error, Heres How to Fix It

Cannot Connect to iTunes Store Error, Heres How to Fix It

When opening the App Store on iPhone, iPad, Mac to download applications or games, the error Cannot Connect to iTunes Store appears and here is the solution.

Useful virtual private networks on Google Chrome

Useful virtual private networks on Google Chrome

VPN (Virtual Private Network) is simply understood as a virtual private network system, capable of creating a network connection based on a certain service provider.