go identifier, variable, constant overview and code demonstration

Posted by pokemon on Sat, 15 Jan 2022 16:37:57 +0100

identifier

In programming language, identifier is a word with special meaning defined by programmer, such as variable name, constant name, function name and so on. In Go language, identifiers are composed of alphanumeric and_ (underline) and can only be composed of letters and_ start. For example: ABC_ 123, a123.

keyword

Keyword refers to a predefined identifier with special meaning in the programming language. Keywords and reserved words are not recommended as variable names.

There are 25 keywords in Go language:

    break        default      func         interface    select
    case         defer        go           map          struct
    chan         else         goto         package      switch
    const        fallthrough  if           range        type
    continue     for          import       return       var

In addition, there are 37 reserved words in the Go language.

    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

Origin of variables

The data during program operation is stored in memory. When we want to operate a data in the code, we need to find the variable in memory. However, if we directly operate the variable through the memory address in the code, the readability of the code will be very poor and error prone, so we use the variable to save the memory address of the data, In the future, you can find the corresponding data in memory directly through this variable.

Variable type

The function of a Variable is to store data. Different variables may hold different data types. After more than half a century of development, programming language has basically formed a set of fixed types. The data types of common variables are integer, floating point, Boolean and so on.

Each variable in the Go language has its own type, and the variable must be declared before it can be used.

Variable declaration

Variables in Go language can only be used after declaration. Repeated declaration is not supported in the same scope. And the variables of Go language must be used after declaration.

Standard statement

The variable declaration format of Go language is:

var Variable name variable type

The variable declaration starts with the keyword var, the variable type is placed after the variable, and there is no semicolon at the end of the line. for instance:

var name string
var age int
var isOk bool

Batch declaration

It is cumbersome to write var keyword for each variable declaration. go language also supports batch variable declaration:

var (
    a string
    b int
    c bool
    d float32
)

Initialization of variables

When the Go language declares a variable, it will automatically initialize the memory area corresponding to the variable. Each variable is initialized to the default value of its type. For example, the default value of integer and floating-point variables is 0. The default value of a string variable is an empty string. Boolean variables default to false. The default of slice, function and pointer variables is nil.

Of course, we can also specify the initial value of a variable when declaring it. The standard format of variable initialization is as follows:

var Variable name type = expression

for instance:

var name string = "Q1mi"
var age int = 18

Or initialize multiple variables at once

var name, age = "Q1mi", 20

Type derivation

Sometimes we omit the type of the variable. At this time, the compiler will deduce the type of the variable according to the value to the right of the equal sign to complete the initialization.

var name = "Q1mi"
var age = 18

Short variable declaration

Inside the function, you can declare and initialize variables in a simpler way: =.

package main

import (
	"fmt"
)
// Global variable m
var m = 100

func main() {
	n := 10
	m := 200 // The local variable m is declared here
	fmt.Println(m, n)
}

Anonymous variable

When using multiple assignment, if you want to ignore a value, you can use anonymous variable. Anonymous variables are underlined_ Indicates, for example:

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

Anonymous variables do not occupy namespaces and do not allocate memory, so there are no duplicate declarations between anonymous variables. (in programming languages such as Lua, anonymous variables are also called dummy variables.)

matters needing attention:

  1. Every statement outside a function must start with a keyword (var, const, func, etc.)
  2. : = cannot be used outside a function.
  3. _ Mostly used for placeholders, indicating that the value is ignored.

constant

Relative to variables, constants are constant values, which are mostly used to define those values that will not change during program operation. The declaration of constants is very similar to that of variables, except that var is replaced by const, and constants must be assigned values when they are defined.

const pi = 3.1415
const e = 2.7182

After the constants pi and e are declared, their values can no longer change during the whole program run.

Multiple constants can also be declared together:

const (
    pi = 3.1415
    e = 2.7182
)

When const declares multiple constants at the same time, if the value is omitted, it means that it is the same as the value in the previous line. For example:

const (
    n1 = 100
    n2
    n3
)

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

iota

iota is a constant counter of go language, which can only be used in constant expressions.

Iota will be reset to 0 when const keyword appears. Each new row constant declaration in const will make iota count once (iota can be understood as the row index in const statement block). Using iota simplifies the definition and is useful in defining enumerations.

for instance:

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

Several common iota examples:

Use_ Skip some values

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

iota declared to jump in the middle of the queue

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

Define the order of magnitude (here < < represents the shift left operation, 1 < < 10 represents the shift left of the binary representation of 1 by 10 bits, that is, from 1 to 100000000, that is, 1024 of the decimal system. Similarly, 2 < < 2 represents the shift left of the binary representation of 2 by 2 bits, that is, from 10 to 1000, that is, 8 of the decimal system.)

const (
		_  = iota
		KB = 1 << (10 * iota)
		MB = 1 << (10 * iota)
		GB = 1 << (10 * iota)
		TB = 1 << (10 * iota)
		PB = 1 << (10 * iota)
	)

Multiple iota s are defined on one line

const (
		a, b = iota + 1, iota + 2 //1,2
		c, d                      //2,3
		e, f                      //3,4
	)

Topics: Go