How to use variables in Golang

In programming languages, identifiers are used for exactly what their name suggests. In other words, identifiers are user-defined names for program elements. In Go, identifiers can be variable names, function names, constants, statement labels, package names, or types. Here's what you need to know about using identifiers in Golang.

How to use variables in Golang

For example:

package main
import "fmt"

func main() {

 var name = "Quantrimang.com"
  
}

There are a total of three identifiers available in the above example:

  • main : Package name
  • main : Name of the function
  • name : Name of the variable

Variable Definition Rules: There are some valid rules for defining valid Go variables. These rules need to be followed, otherwise we will get compilation errors.

  • An identifier name must begin with a letter or an underscore(_). And it can contain the letters 'a-z' or 'A-Z' or the numbers 0-9 as well as the character '_'.
  • The identifier name cannot begin with a digit.
  • Identifier names are case sensitive.
  • Keywords are not allowed as identifiers.
  • There is no limit on the length of an identifier name, but an optimal length of 4 – 15 letters is recommended.

For example:

// Valid identifiers:
_geeks23
geeks
gek23sd
Geeks
geeKs
geeks_geeks

// Invalid identifiers:
212geeks
if
default

Note:

In Go, there are a number of pre-declared identifiers available for constants, types, and functions. These names are not reserved, you are allowed to use them in declarations. Here is a list of pre-declared identifiers:

Cho hằng số:
true, false, iota, nil

Cho các kiểu:
int, int8, int16, int32, int64, uint,
uint8, uint16, uint32, uint64, uintptr,
float32, float64, complex128, complex64,
bool, byte, rune, string, error

Cho các hàm:
make, len, cap, new, append, copy, close, 
delete, complex, real, imag, panic, recover
  • A variable represented by an underscore character (_) is called an empty identifier. It is used as an anonymous placeholder instead of a regular identifier and has special meaning in declarations, as an operand, and in assignments.
  • A variable that is accessible from another package is called an exported identifier. Exported identifiers are those identifiers that satisfy the following conditions:
    • The first character of the exported identifier name must be an uppercase Unicode letter.
    • The identifier must be declared within a package block or as the name of a variable, function, type, or method within that package.

In the example below, file1.go contains an exported variable named ExportedVariable , which is accessible within the same file. It also imports the file2 package and accesses the exported variable AnotherExportedVariable from file2.go . By running go run file1.go , it will print the value of ExportedVariable (“Hello, World!”) from file1.go and the value of AnotherExportedVariable (“Greetings from file2!”) from file2.go . This demonstrates the concept of exported variables being accessible from another package in Go.

Example of file2:

//file2.go

package file2

// Exported variable
var AnotherExportedVariable = "Greetings from file2!"

Example of file1:

// file1.go

package main

import (
	"fmt"
	"github.com/yourusername/project/file2"
)

// Biến được xuất
var ExportedVariable = "Hello, World!"

func main() {
	// Truy cập biến đã xuất trong cùng file
	fmt.Println(ExportedVariable)

	// Truy cập biến đã xuất từ gói khác
	fmt.Println(file2.AnotherExportedVariable)
}

Result:

Hello, World!
Greetings from file2!
Sign up and earn $1000 a day ⋙

Leave a Comment

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.

Variable Scope in Go

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 a lexical scope that is determined at compile 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.

Defer Keyword in Golang

Defer Keyword in Golang

In Go, defer statements delay execution of a function or method or an anonymous method until the nearby functions return.

Methods in Golang

Methods in Golang

Methods in Golang are like functions but with one major difference: they have a receiver argument, which allows access to the properties of the receiver.

Main and init functions in Golang

Main and init functions in Golang

Go language has two special purpose functions and those functions are main() and init(). Here are the things to know about using main() and init() functions in Golang.

Anonymous Functions in Golang

Anonymous Functions in Golang

Anonymous functions in Go are very useful. Below is the syntax, usage and example of using anonymous functions in Golang.

The var keyword in Go

The var keyword in Go

The var keyword in Golang is used to create variables of a specific type with a specific name and initial value. Initialization is optional at the time of declaring the variable using the var keyword in Golang

Nested Structure in Golang

Nested Structure in Golang

Go language allows nested structures. A structure that is a field of another structure is called Nested Structure.

5 Best Google Sheets Add-ons to Make Data Analysis Easier

5 Best Google Sheets Add-ons to Make Data Analysis Easier

Google Sheets is a powerful tool for data analysis, but sometimes you need more power. There are plenty of add-ons that can speed up your spreadsheets and take your data processing to the next level.

The best way to scan and digitize old photos

The best way to scan and digitize old photos

Your precious old photos won't last forever. If you want to preserve your memories from time, damage, and dust, you need to bring them into the digital age.

Instructions to change Messenger color on phone, computer

Instructions to change Messenger color on phone, computer

Messenger has different chat themes for you to set for your chat. In addition to artistic chat themes or specific topics, you can also choose a color theme for Messenger.

How to play the Executioner lineup DTCL season 14

How to play the Executioner lineup DTCL season 14

The Executioner in season 14 stands out with his ability to deal powerful critical damage.

Latest X-Wukong Dai Chien Tam Gioi Code and how to redeem code

Latest X-Wukong Dai Chien Tam Gioi Code and how to redeem code

X-Wukong Dai Chien Tam Gioi gives players Gold, Linh Thach, Hon Ngoc... and many other attractive items through newbie giftcodes and event codes.

Latest Eternal Ember Code and How to Enter Code

Latest Eternal Ember Code and How to Enter Code

Eternal Ember Codes will give gamers currency and loot. Below are the Eternal Ember codes for you to enter and redeem, remember to follow this article for more code updates.

How to add a shared mailbox in Outlook

How to add a shared mailbox in Outlook

Shared mailboxes in Outlook make it easier for people to interact, view content, and share work together.

How to adjust the volume of each Chrome tab up to 600%

How to adjust the volume of each Chrome tab up to 600%

Volume Master is an extension installed on the Chrome browser that can adjust the volume of each separate tab on the browser, up to 600%.

Opera introduces some cool new keyboard shortcuts for the Opera GX browser

Opera introduces some cool new keyboard shortcuts for the Opera GX browser

Opera has introduced some new keyboard shortcuts for the Opera GX browser that bring cat pictures and other relaxing things to you with just a few keystrokes.

Ways to take care of yourself in the fall to stay happy and love life

Ways to take care of yourself in the fall to stay happy and love life

Fall is a great time to reset, slow down, and embrace change. Here are some ways to take care of yourself so you can live a happy, healthy life.

Things to Consider Before Cutting Bangs

Things to Consider Before Cutting Bangs

Should I cut bangs? is something that every girl probably asks herself at least once in her life. Below are some things that will tell you whether you should cut bangs or not.

How to give costumes to friends in Lien Quan

How to give costumes to friends in Lien Quan

Do you know how to give your friends beautiful costumes in Lien Quan? Let's find out now!

Latest Stop Hand Release Code and how to enter code

Latest Stop Hand Release Code and how to enter code

Giai Toa Stop Hand is a tower defense strategy game where you must protect the King's house from monster attacks.

How to use Panasonic air conditioner in the most detailed way

How to use Panasonic air conditioner in the most detailed way

Panasonic air conditioners also have 1-way and 2-way types, using Inverter technology or not... But no matter which type of Panasonic air conditioner, the basic usage is quite similar, the only difference is in the new features on the high-end line.

6 Reasons to Skip Your Smart TV and Buy a Streaming Stick Instead

6 Reasons to Skip Your Smart TV and Buy a Streaming Stick Instead

After dealing with the clunky interface and sluggish performance, many people have finally decided to ditch Smart TV apps altogether and switch to using the Apple TV 4K full-time.