Short variable declaration operator in Go

The short variable declaration operator (:=) in Golang is used to create variables with a specific name and initial value. The main purpose of using this operator is to declare and initialize local variables inside functions and to narrow the scope of variables. The type of the variable is determined by the type of the expression. The var keyword is also used to create variables of a specific type. So you can say that there are two ways to create variables in Golang as follows:

Short variable declaration operator in Go

  • Using the var keyword
  • Use the short variable declaration operator (:=)

Now let's learn how to use the short variable declaration operator in Golang!

Main content

Syntax for using short variable declaration operator in Golang

variable_name := biểu thức hoặc giá trị

Here, you have to initialize the variable immediately after declaration. But using var keyword , you can avoid initialization at the time of declaration. There is no need to mention the type of the variable. The expression or value on the right side is used to evaluate the type of the variable.

For example, here we are declaring variables using the short declaration operator and not specifying the type of the variable. The type of the variable is determined by the type of the expression on the right side of the operator :=.

// Minh họa chương trình Go dùng := (toán tử khai báo ngắn) 
package main

import "fmt"

func main() {

	// khai báo và khởi tạo biến
	a := 30

	// lấy một biến chuỗi
	Language: = "Go Programming"

	fmt.Println("The Value of a is: ", a)
	fmt.Println("The Value of Language is: ", Language)

}

Result:

The Value of a is:  30
The Value of Language is:  Go Programming

Declaring multiple variables using the short declaration operator

The short declaration operator can also be used to declare multiple variables of the same or different types in a single declaration. The types of these variables are evaluated by the expression on the right side of the operator :=.

For example:

// Minh họa chương trình Go dùng toán tử khai báo ngắn := short để khai báo nhiều
// biến thành một câu lệnh khai báo duy nhất
package main

import "fmt"

func main() { 

// nhiều biến của cùng kiểu(int)
geek1, geek2, geek3 := 117, 7834, 5685

// nhiều biến của các kiểu khác nhau
geek4, geek5, geek6 := "GFG", 859.24, 1234

// Hiện giá trị và kiểu của biến
fmt.Printf("The value of geek1 is : %d\n", geek1) 
fmt.Printf("The type of geek1 is : %T\n", geek1) 

fmt.Printf("\nThe value of geek2 is : %d\n", geek2) 
fmt.Printf("The type of geek2 is : %T\n", geek2) 

fmt.Printf("\nThe value of geek3 is : %d\n", geek3) 
fmt.Printf("The type of geek3 is : %T\n", geek3)

fmt.Printf("\nThe value of geek4 is : %s\n", geek4) 
fmt.Printf("The type of geek4 is : %T\n", geek4)


fmt.Printf("\nThe value of geek5 is : %f\n", geek5) 
fmt.Printf("The type of geek5 is : %T\n", geek5)

fmt.Printf("\nThe value of geek6 is : %d\n", geek6) 
fmt.Printf("The type of geek6 is : %T\n", geek6)

} 

Result:

The value of geek1 is : 117
The type of geek1 is : int

The value of geek2 is : 7834
The type of geek2 is : int

The value of geek3 is : 5685
The type of geek3 is : int

The value of geek4 is : GFG
The type of geek4 is : string

The value of geek5 is : 859.240000
The type of geek5 is : float64

The value of geek6 is : 1234
The type of geek6 is : int

Important points to remember:

The short declaration operator can be used when at least one variable on the left side of the operator :=is newly declared. The short variable declaration operator works like an assignment to variables that have been declared in the same lexical block. To understand this concept better, let's take an example.

Example 1: The program below will throw an error because there is no new variable on the left side of the operator :=.

// Minh họa chương trình Go dùng khai báo biến ngắn
package main

import "fmt"

func main() { 

	// lấy hai biến
	p, q := 100, 200

	fmt.Println("Value of p ", p, "Value of q ", q)

	// Báo lỗi vì không có biến mới ở bên tay trái của :=
	p, q := 500, 600
	
	fmt.Println("Value of p ", p, "Value of q ", q)
}

Error:

./prog.go:17:10: no new variables on left side of := 

Example 2:

In the program below, you can see the line geek3, geek2 := 456, 200 will work fine without any error because there is at least one new variable i.e. geek3 on the left side of the operator :=.

// Chương trình Go dùng toán tử khai báo biến ngắn
package main 

import "fmt"

func main() { 

// Ở đây, khai báo biến ngắn hoạt động
// như một phép gán cho biến geek1
// vì cùng một biến có trong cùng một khối
// do đó giá trị của geek2 được thay đổi từ 100 thành 200
geek1, geek2 := 78, 100

// ở đây, := được sử dụng như một phép gán cho geek2
// vì nó đã được khai báo. Ngoài ra, dòng này
// sẽ hoạt động tốt vì geek3 mới được tạo
// biến
geek3, geek2 := 456, 200

// Nếu bạn thử chạy các dòng được chú thích,
// thì trình biên dịch sẽ báo lỗi vì
// các biến này đã được định nghĩa
// geek1, geek2 := 745, 956
// geek3 := 150

// Hiện giá trị của các biến
fmt.Printf("The value of geek1 and geek2 is : %d %d\n", geek1, geek2) 
											
fmt.Printf("The value of geek3 and geek2 is : %d %d\n", geek3, geek2) 
} 

Result:

The value of geek1 and geek2 is : 78 200
The value of geek3 and geek2 is : 456 200

Go is a strongly typed language because you cannot assign a value of a different data type to a declared variable.

For example:

// Minh họa chương trình Go dùng toán tử khai báo biến ngắn
package main 

import "fmt"

func main() { 

	// lấy một biến của int
	z := 50
	
	fmt.Printf("Value of z is %d", z)
	
	// gán lại giá trị của kiểu chuỗi
// nó sẽ đưa ra lỗi
	z := "Golang"
} 

Error:

./prog.go:16:4: no new variables on left side of := 
./prog.go:16:7: cannot use “Golang” (type string) as type int in assignment 
 

In a short variable declaration, Golang allows initializing a set of variables using a function call that returns multiple values. Or you can say variables can also be assigned values ​​that are evaluated at runtime.

For example:

// Tại đây, hàm math.Max function trả về
// số lớn nhất trong biến i 
i := math.Max(x, y)

Local variable or global variable

With the help of short declaration operator (:=), you can declare local variables whose scope is only at the block level. Generally, local variables are declared inside the function block. If you try to declare global variables using short declaration operator then you will get an error.

Example 1:

// Chương trình Go hiển thị cách sử dụng toán tử :=
// để khai báo các biến cục bộ
package main

import "fmt"

// sử dụng từ khóa var để khai báo
// và khởi tạo biến
// đó là package hoặc bạn có thể nói
// phạm vi cấp toàn cục
var geek1 = 900

// sử dụng khai báo biến ngắn
// sẽ báo lỗi
geek2 := 200

func main() {

// truy cập geek1 bên trong hàm
fmt.Println(geek1)

// truy cập geek2 bên trong hàm
fmt.Println(geek2)

}

Error:

./prog.go:15:1: syntax error: non-declaration statement outside function body 

Example 2:

// Chương trình Go dùng toán tử := operator
// để khai báo các biến cục bộ
package main 

import "fmt"

// dùng từ khóa var để khai báo
// và khởi tạo biến
// nó đóng gói hoặc bạn có thể báo
// phạm vi cấp toàn cục
var geek1 = 900


func main() { 

// dùng khai báo biến ngắn
// bên trong hàm chính
// nó có phạm vi cục bộ tức là không thể
// truy cập bên ngoài hàm chính
geek2 := 200

// truy cập geek1 bên trong hàm n��y
fmt.Println(geek1) 

// truy cập geek2 bên trong hàm này
fmt.Println(geek2) 
	
} 

Result:

900
200
Sign up and earn $1000 a day ⋙

Leave a Comment

What is the flower of the other shore? Meaning and legend of the flower of the other shore

What is the flower of the other shore? Meaning and legend of the flower of the other shore

The flower of the other shore is a unique flower, carrying many unique meanings. So what is the flower of the other shore, is the flower of the other shore real, what is the meaning and legend of the flower of the other shore?

Healthy snacks that help you lose weight

Healthy snacks that help you lose weight

Craving for snacks but afraid of gaining weight? Dont worry, lets explore together many types of weight loss snacks that are high in fiber, low in calories without making you try to starve yourself.

What to do when you have trouble sleeping?

What to do when you have trouble sleeping?

Prioritizing a consistent sleep schedule and evening routine can help improve the quality of your sleep. Heres what you need to know to stop tossing and turning at night.

How to add a printer to Windows 10

How to add a printer to Windows 10

Adding a printer to Windows 10 is simple, although the process for wired devices will be different than for wireless devices.

The most commonly deficient nutrients in the diet

The most commonly deficient nutrients in the diet

Diet is important to our health. Yet most of our meals are lacking in these six important nutrients.

How to get beautiful nails quickly

How to get beautiful nails quickly

You want to have a beautiful, shiny, healthy nail quickly. The simple tips for beautiful nails below will be useful for you.

The best laptops for students in 2025

The best laptops for students in 2025

Students need a specific type of laptop for their studies. It should not only be powerful enough to perform well in their chosen major, but also compact and light enough to carry around all day.

Ways to reduce the risk of birth defects in the fetus

Ways to reduce the risk of birth defects in the fetus

Birth defects are something no one wants. Although they cannot be completely prevented, you can take the following steps to reduce the risk of birth defects in your baby.

How to check RAM and check RAM errors on your computer with the highest accuracy rate

How to check RAM and check RAM errors on your computer with the highest accuracy rate

As you know, RAM is a very important hardware part in a computer, acting as memory to process data and is the factor that determines the speed of a laptop or PC. In the article below, WebTech360 will introduce you to some ways to check for RAM errors using software on Windows.

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!