Basic use of variables in Golang series

1. Definition of variables

No matter which high-level language is used, variables are the basic unit of the program. Variable means that in memory, the program can apply for a piece of data storage space by defining a variable, and then use this storage space by referencing the variable name.

2. Steps for using variables

  • Declare variable
  • Initialization or assignment
  • Use variables
package main
import "fmt"
func main() {
	var i int
	i = 10
	fmt.Println("i=" + i);
}

3. Variable declaration

Basic syntax: var [variable name] [type]

eg: var a int declares a variable a of type int

Multivariable declaration. go supports the declaration of multiple variables with one var, just use parentheses

var (
	v1 int
	v2 string
)

4. Variable initialization

There are three ways to initialize variables

// Mode 1: routine operation, according to the specification
var v1 int = 1
// Method 2: omit the type, and the editor will locate it as int type according to the assignment
var v2 = 1
// Method 3: omit var and type, and the editor automatically deduces int type
v2 := 1

Go language does not write types, which is a bit like dynamic languages such as JavaScript, but go is a static language because the go editor will deduce types according to the assignment

Note: when using the: = symbol, it should be noted that the variable to the left of the: = symbol should be undeclared, otherwise an error will be reported

var a int
a := 1

no new variables on left side of :=

5. Variable assignment

Variable initialization and operation are two different concepts. Initialization is only once, and assignment can be multiple times

var v1 int 
v1 = 10

Note that variables cannot be changed arbitrarily

var a int = 1
a = 2
a = 3
// The variable has been defined as int type and cannot be changed to float
a = 3.1

Exception prompt: constant 3.1 truncated to integer

  • Variable multiple assignment
    go provides a good multi assignment function. With multi assignment, two variables can be interchanged
i, j = j, i

Languages without this function, such as PHP or java, can only be exchanged through a temporary variable

temp = i;
i = j;
j = temp;

6. Anonymous variable

Anonymous variables are underlined_ To declare, the value given to it will be discarded. The advantage of this variable is that it can avoid declaring too many variables and only declare the variables that need to be called. In other languages, sometimes functions return multiple values and need to define multiple variables to receive. go language provides this method for processing

func main() {
	// Get only the required user name
	userName,_ := GetUserInfo()
	fmt.Println(userName)
}
func GetUserInfo() (userName string , password string) {
	return "admin", "pwd"
}

7. Scope of variable

Like other languages, go also has global variables and local variables. All variables declared outside the function body are global variables. This variable can be used in the whole file. If you want to call across packages or files, it must be declared in uppercase, which is somewhat similar to the public variable in java. After being declared as a global variable of size, it can be called in other packages; Then, the local variable is the variable declared in the function body. The local variable can only be called in the corresponding function

8. Use of constants

In go language, constants refer to values that are known at compile time and cannot be changed. Constants can only be scalar types such as numeric types (including integer, floating-point and complex types), Boolean types and string types.

Const is often used for declaration. The syntax is const [constant name] [type]. Sometimes the type can be omitted and assigned directly. The go editor will deduce it by itself

  • Define multiple constants
const (
	size int64 = 1024
	flag = -1
)
  • Multiple assignment
const a,b,c = 1 , 2, "foo"
  • Predefined Constants
    The Go language predefines these constants: true, false, and iota. True and false are common. Let's take a look at iota

  • iota constant generator
    Constant declarations can be data initialized using the iota constant generator to generate a set of constants initialized with similar rules. Generally, it will be initialized to 0 after const declaration. Before the next const declaration, each call will be assigned according to the rules

const (
	c1 = iota // 0
	c2 = iota // 1
	c3 = iota // 2
)

const (
	c4 = 1 << iota // 1 
	c5 = 1 << iota // 2
	c6 = 1 << iota // 4
)

const (
	c7 = iota * 2 // 0
	c8 = iota * 2 // 2
	c9 = iota * 2 // 4
)

const a = iota // 0

const multiple assignment. If the two assignment expressions are the same, they can be omitted, so the above example can be modified

const (
	c1 = iota // 0
	c2        // 1
	c3		  // 2
)

const (
	c4 = 1 << iota // 1
	c5			   // 2
	c6             // 4
)

const (
	c7 = iota * 2 // 0
	c8            // 2
	c9            // 4
)

Using this feature, you can define multiple constants, which can achieve the effect similar to enumeration in java. The following code defines constants and assigns values in the order of 0 ~ 6

type Weekday int

const (
	Sunday Weekday = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
)

There are more complicated examples from the go language Bible

const (
	_ = 1 << (10 * iota)
	KiB // 1024
	MiB // 1048576
	GiB // 1073741824
	TiB // 1099511627776             (exceeds 1 << 32)
	PiB // 1125899906842624
	EiB // 1152921504606846976
	ZiB // 1180591620717411303424    (exceeds 1 << 64)
	YiB // 1208925819614629174706176
)
  • Constant scope
    The scope of constants is also determined according to the case. Uppercase constants can be called in this package, and lowercase constants can only be called in this package

Keywords: Go Back-end

Added by astarmathsandphysics on Sun, 23 Jan 2022 09:10:00 +0200