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

Top 5 best automatic home coffee makers

Top 5 best automatic home coffee makers

The automatic home coffee maker is a modern and professional product, bringing you and your family delicious cups of coffee with just a few quick steps.

Difference between regular TV and Smart TV

Difference between regular TV and Smart TV

Smart TVs have really taken the world by storm. With so many great features and the ability to connect to the Internet, technology has changed the way we watch TV.

Why doesnt the freezer have a light but the refrigerator does?

Why doesnt the freezer have a light but the refrigerator does?

Refrigerators are familiar appliances in families. Refrigerators usually have 2 compartments, the cool compartment is spacious and has a light that automatically turns on every time the user opens it, while the freezer compartment is narrow and has no light.

2 Ways to Fix Network Congestion That Slows Down Wi-Fi

2 Ways to Fix Network Congestion That Slows Down Wi-Fi

Wi-Fi networks are affected by many factors beyond routers, bandwidth, and interference, but there are some smart ways to boost your network.

How to Downgrade from iOS 17 to iOS 16 without Losing Data using Tenorshare Reiboot

How to Downgrade from iOS 17 to iOS 16 without Losing Data using Tenorshare Reiboot

If you want to go back to stable iOS 16 on your phone, here is the basic guide to uninstall iOS 17 and downgrade from iOS 17 to 16.

What happens to the body when you eat yogurt every day?

What happens to the body when you eat yogurt every day?

Yogurt is a great food. Is it good to eat yogurt every day? What will happen to your body when you eat yogurt every day? Let's find out together!

Which type of rice is best for health?

Which type of rice is best for health?

This article discusses the most nutritious types of rice and how to maximize the health benefits of whichever rice you choose.

How to wake up on time in the morning

How to wake up on time in the morning

Establishing a sleep schedule and bedtime routine, changing your alarm clock, and adjusting your diet are some of the measures that can help you sleep better and wake up on time in the morning.

Rent Please! Landlord Sim Tips for Beginners

Rent Please! Landlord Sim Tips for Beginners

Rent Please! Landlord Sim is a simulation mobile game on iOS and Android. You will play as a landlord of an apartment complex and start renting out an apartment with the goal of upgrading the interior of your apartments and getting them ready for rent.

Latest Bathroom Tower Defense Codes and How to Enter Codes

Latest Bathroom Tower Defense Codes and How to Enter Codes

Get Bathroom Tower Defense Roblox game codes and redeem them for exciting rewards. They will help you upgrade or unlock towers with higher damage.

Structure, symbols and operating principles of transformers

Structure, symbols and operating principles of transformers

Let's learn about the structure, symbols and operating principles of transformers in the most accurate way.

4 Ways AI Is Making Smart TVs Better

4 Ways AI Is Making Smart TVs Better

From better picture and sound quality to voice control and more, these AI-powered features are making smart TVs so much better!

Why ChatGPT is better than DeepSeek

Why ChatGPT is better than DeepSeek

DeepSeek initially had high hopes. As an AI chatbot marketed as a strong competitor to ChatGPT, it promised intelligent conversational capabilities and experiences.

Meet Fireflies.ai: The Free AI Secretary That Saves You Hours of Work

Meet Fireflies.ai: The Free AI Secretary That Saves You Hours of Work

It's easy to miss important details when you're jotting down other essentials, and trying to take notes while chatting can be distracting. Fireflies.ai is the solution.

How to raise Axolotl Minecraft, tame Minecraft Salamander

How to raise Axolotl Minecraft, tame Minecraft Salamander

Axolot Minecraft will be a great assistant for players when operating underwater if they know how to use them.