Go Language Variables and Constants

Posted by Decipher on Mon, 03 Jan 2022 22:39:02 +0100

identifier

Programmer-defined words in programming languages that have special meaning, such as variable names, constant names, function names, and so on. Identifiers in the Go language are alphabets, numbers, and _ (Underline) and can only start with a letter and an underscore. For example: abc, _abc, _123, a123.

Keyword

A pre-defined identifier in a programming language that has some special meaning. Keyword reserved words are not recommended as variable names.

The Go language has 25 keywords:

Name	describe
break	Force exit from loop or switch Statement block
case	Be used for switch and select Statement block followed by an expression to indicate a match
chan	For definition channel Keyword
const	Constant keywords
continue	Skip this cycle and move on to the next iteration
default	switch and switch Default items defined in statement blocks
defer	Delayed Call Keyword
else	Select the key words of the judgement statement
fallthrough	switch Make one in a statement block case When the subblock is finished, proceed to the next one case Code for subblocks
for	Loop body statement block keywords
func	Keyword defining functions and methods
go	Definition goroutine Keyword
goto	Process Control Keyword, which tells the program execution process to jump to an exact location
if	Select the key words of the judgement statement
import	Import Package
interface	Interface type
map	Built-in map type
package	Define Package Name
range	Define an iteration range, commonly used in loop statement blocks
return	End function assignment so that function returns
select	Keyword used to define communication control structure
struct	Structural structure keywords
switch	Multiple Selection Decision Structure Statement Block Keyword
type	Custom Type Keyword
var	Variable Definition Keyword

37 reserved words:

    Constants:    true  false  iota  nil

    Types:    int  int8  int16  int32  int64  
              uint  uint8  uint16  uint32  uint64  uintptr
              float32  float64  complex128  complex64
              bool  byte  rune  string  error

    Functions:   make  len  cap  new  append  copy  close  delete
                 complex  real  imag
                 panic  recover

Variable type

The function of a Variable is to store data. Common data types are integer, floating point, Boolean, and so on.

Variable declaration

Standard Statement

Variables in the Go language must be declared before they can be used. GoLanguage variable declaration format:

var Variable Name Variable Type

Variable declarations begin with var, variable types follow variable names, and line endings do not require semicolons, for example:

var name string
var age int
var isOK bool	

Batch Statement

var(
	name string
	age int
	isOK bool
)

Example:

package main

import "fmt"

//The hump command is recommended in the Go language
//var student_name string underline
//var studentName string hump (recommended)
//var StudentName string

//Declare Variables
var (
	name string
	age  int
	isOK bool
)

func main() {
	name = "Aston"
	age = 34
	isOK = true
    
    //Non-global variable declarations in Go must be used, not compiled
    
	fmt.Printf("name:%s", name) //%s: Placeholder, replace the placeholder with the value of the name variable
    fmt.Println()               //Quick Print of Empty Lines
	fmt.Println(age)            //After printing the specified content, a line break will be appended to it
	fmt.Print(isOK)             //Output to print in terminal without line breaks
}

output:

name:Aston
34
true

Variable Initialization

When you declare a variable, the Go language automatically initializes the memory area corresponding to the variable. Each variable is initialized to its type's default value. For example, integer and floating-point defaults are 0, string defaults are empty strings, Boolean defaults are false, and slice, function, and pointer variables are nil. Of course, we can assign values to variables when they are declared. The standard format for variable initialization is:

var Variable Name Type= Expression	

For example:

//Assignment while declaring variables
var s1 string= "hooo"
fmt.Println(s1)

//Type Deduction: Determine what type of variable it is based on its value
var s2= "hooo2"
fmt.Println(s2)

//Short variable declaration: can only be used in functions
s3:= "hahaha"
fmt.Println(s3)

//Note: Variables with the same name cannot be declared repeatedly in the same scope.

Or initialize multiple variables at once

var name, age= "hooo", 18	

Anonymous variable

When using multiple assignments, anonymous variables can be used if you want to ignore a value. anonymous variable with an underscore_ Represents, for example:

func foo(int, string){
	return 10, "hooo"
}
func main(){
	x, _= foo()
	_, y= foo()
	fmt.Println("x=", x)
	fmt.Println("y=", y)
}

Anonymous variables do not take up namespace and allocate memory, so there is no duplicate declaration between anonymous variables.

Matters needing attention:

  1. Every statement outside a function must start with a keyword (var, const, func, etc.);
  2. :=can no longer be used outside of a function;
  3. _ Used mostly for placeholders, indicating ignore values.

constant

Constants are invariant values relative to variables and are used to define those values that will not change during program execution. The declaration of a constant is very similar to the declaration of a variable, except that the var is changed to a const, and the constant must be assigned when it is defined.

const pi= 3.1415
const e= 2.7182

After the values pi and e have been declared, their values cannot be changed during the entire program run.

Example:

package main

import "fmt"

//constant
//Once a constant is set, it cannot be modified and will not change during the program's run
const pi = 3.1415926

func main() {
	fmt.Println(pi)
}

const can declare multiple constants at the same time, if the value representation is omitted, it is the same as the value in the previous row. For example:

const(
	n1= 100
	n2
	n3
)

In the example, the values of the constants n1,n2,n3 are all 100.

iota

iota is a constant counter for the Go language and can only be used in constant expressions.

Iota is reset to zero when the const keyword appears. Each new row constant declaration in a const counts the iota once (iota is understood as a row index in a const statement block). Using iota simplifies the definition and is useful when defining enumerations.

Example:

const(
	n1= iota 	//0
	n2		    //1	
	n3          //2
	n4          //3
)

Several common examples:

const(
	b1= iota //0
	b2 //1
	_
	b3 //3
)
const(
	c1= iota //0
	c2= 100  //100
	c3       //100
	c4= iota //3
)
const(
	d1, d2= iota+ 1, iota+ 2  //d1=1, d2=2
	d3, d4= iota+ 3, iota+ 4  //d3=4, d4=5
)

Define the order of magnitude:

const(
_= iota
KB= 1<< (10* iota)  //1 Shift 10 Bits Left
MB= 1<< (10* iota)
GB= 1<< (10* iota)
TB= 1<< (10* iota)
PB= 1<< (10* iota)
)