Go language based variables and constants

Identifiers and keywords

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 start with a letter and. For example: abc,,, 123, a123.

keyword

Keywords refer to pre-defined identifiers with special meanings in the programming language. Neither keywords nor reserved words are recommended to be used 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
 Copy code

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
 Copy code

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 variables is to store data. Different variables may save different data types. After more than half a century of development, programming languages have basically formed a set of fixed types. The data types of common variables are integer, floating point, Boolean, etc.

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. Moreover, variables in Go language must be used after declaration.

Standard statement

The variable declaration format of Go language is:

var Variable name variable type
 Copy code

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 example:

var name string
var age int
var isOk bool
 Copy code

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
)
Copy code

Initialization of variables

When declaring variables, Go language will automatically initialize the memory area corresponding to the variables. Each variable will be 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 string variables is empty string. The default value of Boolean variables is false. The default value of slice, function and pointer variables is nil. Of course, we also You can specify an initial value for a variable when it is declared. The standard format for variable initialization is as follows:

var Variable name type = expression
 Copy code

for instance:

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

Or initialize multiple variables at once

var name, age = "Q1mi", 20
 Copy code

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
 Copy code

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)
}
Copy code

Anonymous variable

When using multiple assignment, if you want to ignore a value, you can use anonymous variable. Anonymous variables are represented by an underscore such as:

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

Anonymous variables do not occupy namespaces and do not allocate memory, so there are no duplicate declarations between anonymous variables. (anonymous variables are also called dummy variables in programming languages such as Lua.) 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

Compared with 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 during definition.

const pi = 3.1415
const e = 2.7182
 Copy code

After the constants pi and e are declared, their values cannot change during the whole program running. Multiple constants can also be declared together:

const (
    pi = 3.1415
    e = 2.7182
)
Copy code

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
)
Copy code

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 the const keyword appears. Each new row constant declaration in const will count iota once (iota can be understood as the row index in the const statement block). Using iota can simplify the definition and is very useful in defining enumeration.

for instance:

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

Several common iota examples:

Use to skip some values

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

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
 Copy code

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)
	)
Copy code

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
	)

Added by Mikersson on Sat, 11 Dec 2021 04:47:06 +0200