Variable Scope in Go

The scope of a variable in Golang  determines which part of the program the variable is accessible to. In Go, all identifiers have lexical scope, meaning the scope can be determined at compile time. A variable is only accessible within the block of code in which it is defined.

Variable Scope in Go

For example:

package main  
import "fmt"

// Khai báo biến toàn cụ
var myVariable int = 100 

func main() {
    // Biến cục bộ trong hàm chính
    var localVar int = 200 
    fmt.Printf("Inside main - Global variable: %d\n", myVariable) 
    fmt.Printf("Inside main - Local variable: %d\n", localVar) 
    display() 
}

func display() {
    fmt.Printf("Inside display - Global variable: %d\n", myVariable) 
}

Variable scope syntax in Golang

var variableName type = value 

Local variables

Local variables are declared within a function or a block and cannot be accessed outside that block. They can also be declared within loops and conditionals but are limited to the scope of the block.

For example:

package main
import "fmt"

func main() {
    var localVar int = 200 // Biến cục bộ
    fmt.Printf("%d\n", localVar) // Có thể truy cập tại đây
}

Result:

200

Global variables

Global variables are defined outside any function or block, making them accessible throughout the entire program.

For example:

package main
import "fmt"

// Khai báo biến toàn cục
var myVariable int = 100 // Biến toàn cục

func main() {
    fmt.Printf("%d\n", myVariable) // Có thể truy cập tại đây
}

Result:

100

Local variable priority

When a local variable has the same name as a global variable, the local variable takes precedence within its scope.

For example:

package main
import "fmt"

// Khai báo biến toàn cục
var myVariable int = 100 // Biến toàn cục
func main() {
    var myVariable int = 200 // Biến cục bộ
    fmt.Printf("Local variable takes precedence: %d\n", myVariable) // Truy cập biến cục bộ
}

Result:

Biến cục bộ có mức độ ưu tiên: 200
Sign up and earn $1000 a day ⋙

Leave a Comment

Function arguments in Golang

Function arguments in Golang

Go supports two main ways to pass arguments: Pass by Value and Pass by Reference. Go uses pass by value by default.

Function returning multiple values ​​in Golang

Function returning multiple values ​​in Golang

In Go language, you are allowed to return multiple values ​​from a function, using the return statement. In other words, in a function, a return statement can return multiple values.

Switch Statement in Go

Switch Statement in Go

Golang like most other programming languages ​​has switch statement. Here is how to use switch statement in Golang.

Cases to know when using selection statements in Golang

Cases to know when using selection statements in Golang

In this article, we will learn how to use default case to avoid deadlock. But first, we will learn what is deadlock case when using select command in Golang?

Anonymous structures and fields in Golang

Anonymous structures and fields in Golang

Anonymous structs in Golang are temporary structures with no names used for one-time purposes, while anonymous fields allow embedding of unnamed fields.

How to use Rune in Golang

How to use Rune in Golang

What is Rune in Golang? How to use Rune in Golang? This article will give you the answer.

How to use operators in Golang

How to use operators in Golang

Operators allow us to perform different types of operations on operands. In Go language, operators can be classified based on their different functions.

Void identifier in Golang

Void identifier in Golang

_(underscore) in Golang is called Blank Identifier. Identifier is a user-defined name of program elements used for identification purposes.

How to create basic program in Golang

How to create basic program in Golang

Hello, World! is the first basic program in any programming language. You can write this first program in Golang by following the steps below.

How to Install Go on Windows

How to Install Go on Windows

Golang can be easily installed on Windows. Here is a step-by-step guide to install Golang on Windows.

Methods with the same name in Golang

Methods with the same name in Golang

Golang allows creating two or more methods with the same name in the same package, but the receivers of these methods must be of different types.

Functions in Go

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.

Control Statements in Golang (if, if-else, Nested-if)

Control Statements in Golang (if, if-else, Nested-if)

What conditional statements does Golang have? How to use conditional statements in Go programming? Let's find out together!

Short variable declaration operator in Go

Short variable declaration operator in Go

The short variable declaration operator (:=) in Golang is used to create variables with a proper name and initial value. Here is what you need to know about the short variable declaration operator in Golang.

Why are many people still hesitant to buy foldable screen phones?

Why are many people still hesitant to buy foldable screen phones?

Despite the advancements that the foldable display format has made over the past few years, many people are still hesitant to buy a foldable phone for the following reasons...

How to Fix Installation Error 0x800f081f on Windows 11

How to Fix Installation Error 0x800f081f on Windows 11

When trying to update your PC, error code 0x800f081f can cause trouble and prevent you from performing the system update.

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.

Samsung Galaxy Tab S10: Configuration, expected release date

Samsung Galaxy Tab S10: Configuration, expected release date

The Galaxy Tab S10 is sure to be one of the top products on the market when it launches.

Google Accidentally Published Documentation on How Search Works

Google Accidentally Published Documentation on How Search Works

On Monday, internal documents describing the factors Google Search considers when ranking and displaying web results were leaked.

New Alternative Browsers to Chrome You Should Try Today

New Alternative Browsers to Chrome You Should Try Today

Google Chrome is the world's most popular browser, but that doesn't mean you have to use it. There are plenty of great Chrome alternatives that will help you leave Google behind for good, and here are the best.

How to use Microsoft Words voice typing feature

How to use Microsoft Words voice typing feature

If you're someone who spends a lot of time writing, you'll find Word's dictation tool to be a real game changer.

El Nino weakens, will the heat end soon?

El Nino weakens, will the heat end soon?

The World Meteorological Organization (WMO) recently said that global temperatures will ease somewhat after months of record heat waves due to the weakening of the El Nino phenomenon, combined with the return of the La Nina weather pattern.

The worlds longest 240km straight road without a single bend

The worlds longest 240km straight road without a single bend

The title of the longest straight stretch of road in the world belongs to a nearly 240km long highway that cuts through the vast Rub-al-Khali desert in Saudi Arabia, as it has no curves or turns.

How to search chat content on ChatGPT

How to search chat content on ChatGPT

If you are using ChatGPT on the web, you can quickly search for chat content that you have done before, through the keywords you enter.

Summary of the latest Than Ma: Tam Quoc Xuat Chinh codes

Summary of the latest Than Ma: Tam Quoc Xuat Chinh codes

Let's explore the latest Than Ma: Tam Quoc Xuat Chinh code set in this article.

How to change the clock position on the status bar of Samsung phones

How to change the clock position on the status bar of Samsung phones

By default, we cannot change the clock position on Samsung Galaxy phones. But with the Good Lock application from the Galaxy Store, users can choose a different position for the clock on the status bar.

The best love confessions to easily win his heart

The best love confessions to easily win his heart

What are the best love confessions from men that make her fall in love? This article will summarize for you love confessions, good love confessions to your girlfriend on Valentine's Day!

How to split computer screen

How to split computer screen

Splitting the computer screen makes it easier for us to work when we want to compare content.

How to get birthday reminders from Google Assistant

How to get birthday reminders from Google Assistant

Learn how to get birthday reminders from Google Assistant.