Functions in Go

In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Golang functions may or may not return a value to the caller.

Functions in Go

Things to know about functions in Golang

For example:

package main
import "fmt"

// multiply() nhân 2 số nguyên và trả về kết quả
func multiply(a, b int) int {
    return a * b
}

func main() {
    result := multiply(5, 10)
    fmt.Printf("multiplication: %d", result)
}

Result:

multiplication: 50

Function syntax in Golang

func function_name(Parameter-list)(Return_type) {
    // function body...
}

Function declaration

In Go, a function is declared with the func keyword, followed by a name, parameters, and optional return type.

Syntax

func function_name(Parameter-list)(Return_type) {
    // function body...
}

Multiply function example

func multiply(a, b int) int {
    return a * b
}

func: Keyword to declare a function.
function_name: Name of the function, for example: multiply.
Parameter-list: a, b int—the parameters along with their types.
Return_type: int specifies the return type.

Call function

To use a function, simply call it by its name with any necessary arguments. Here, multiply(5, 10) calls the function with 5 and 10 as arguments.

For example

result := multiply(5, 10)
fmt.Printf("Result of multiplication: %d", result)

Function arguments

Go supports two ways to pass parameters to a function: Call by value and Call by reference. By default, Go uses call by value, which means that values ​​are copied and changes inside the function do not affect the caller's variables.

Call by value

In call by value, the values ​​of the arguments are copied into the function parameters, so changes in the function do not affect the original variables.

For example:

package main
import "fmt"

func multiply(a, b int) int {
    a = a * 2 // chỉnh sửa bên trong hàm này
    return a * b
}

func main() {
    x := 5
    y := 10
    fmt.Printf("Before: x = %d, y = %d\n", x, y)
    result := multiply(x, y)
    fmt.Printf("multiplication: %d\n", result)
    fmt.Printf("After: x = %d, y = %d\n", x, y)
}

Result:

Before: x = 5, y = 10
multiplication: 100
After: x = 5, y = 10

Call by reference

In call by reference, pointers are used so that changes inside the function are reflected in the caller's variables.

For example:

package main
import "fmt"

func multiply(a, b *int) int {
    *a = *a * 2 // chỉnh sửa giá trị của a ở địa chỉ bộ nhớ của nó
    return *a * *b
}

func main() {
    x := 5
    y := 10
    fmt.Printf("Before: x = %d, y = %d\n", x, y)
    result := multiply(&x, &y)
    fmt.Printf("multiplication: %d\n", result)
    fmt.Printf("After: x = %d, y = %d\n", x, y)
}

Result

Before: x = 5, y = 10
multiplication: 100
After: x = 10, y = 10
Sign up and earn $1000 a day ⋙

Leave a Comment

How to make cleaning fun

How to make cleaning fun

Cleaning doesn't have to be a chore if you know how to make it fun. Here are some simple ways to make cleaning fun.

What is the Infinity Fortress in Demon Slayer?

What is the Infinity Fortress in Demon Slayer?

Demon Slayer: Infinity Fortress is getting a lot of attention from fans. So what's inside Demon Slayer's Infinity Fortress? Let's find out together!

ChatGPT May Be Running Silently on Your Phone and How to Fix It

ChatGPT May Be Running Silently on Your Phone and How to Fix It

Background Conversations keep a user's conversation with ChatGPT going while using other apps or when the screen is off. This means ChatGPT can listen or monitor a user's phone usage behavior 24/7.

Googles Gemini Responds With Weird, Repeated Nonsense Words to Some Users

Googles Gemini Responds With Weird, Repeated Nonsense Words to Some Users

Recently, some users noticed that Google Gemini has been giving repetitive text, weird characters, and complete nonsense in some responses.

Full code of Luc Tung Tam Quoc latest and instructions to redeem code

Full code of Luc Tung Tam Quoc latest and instructions to redeem code

Code Luc Tung Tam Quoc gives new players everything they need to start their journey.

Code Giang Ho Ngu Tuyet and how to enter code

Code Giang Ho Ngu Tuyet and how to enter code

Giang Ho Ngu Tuyet is an MMORPG game based on the five elements of mutual generation and mutual inhibition. With 5 sects: Shaolin, Minh Giao, Vo Dang, Duong Gia, Thien Nhan based on the five elements of Metal, Wood, Water, Fire, Earth.

MIUI 13 Wallpaper, MIUI 13 Wallpaper

MIUI 13 Wallpaper, MIUI 13 Wallpaper

MIUI 13 wallpapers with many different wallpaper themes from abstract to landscape, combined with vivid and attractive colors for users to choose from.

How to fix Your virus & threat protection is managed by your organization error

How to fix Your virus & threat protection is managed by your organization error

What do you need to do to resolve the error Your virus & threat protection is managed by your organization?

How to fix Chromebook not turning on

How to fix Chromebook not turning on

If your Chromebook won't turn on, you're probably feeling frustrated and hopeless. Luckily, many of the reasons why a Chromebook won't turn on are easy to fix.

Why should you always check app permissions before pressing install?

Why should you always check app permissions before pressing install?

Taking a moment to review your app permissions can save you a lot of privacy and security problems later on!

How to play Rengar DTCL season 14, standard items, lineup...

How to play Rengar DTCL season 14, standard items, lineup...

Rengar DTCL season 14 will play the main assassin role, with the ability to jump to the enemy with the lowest health and deal strong physical damage.

Can autism be detected based on facial features?

Can autism be detected based on facial features?

Using facial features to detect autism is a growing area of ​​research. While it can aid in diagnosis, much of the research remains unreliable.

10 types of diseases caused by technology, only appear in modern people

10 types of diseases caused by technology, only appear in modern people

Technology brings convenience and unlimited connectivity, changing everyone's lives but also bringing diseases that were never seen before.

How to move purchases between 2 Apple accounts

How to move purchases between 2 Apple accounts

If you've purchased apps, subscriptions, music, videos, or other content from one Apple account, you can now transfer purchases to another Apple account when needed.

How to hide personal information of photos on phone

How to hide personal information of photos on phone

Skitch application on Android, iOS will edit images including the feature of blurring out personal and confidential information in the image.