DataWhale & Golang (three, variables, constants, enumerations)

DataWhale & Golang (three, variables, constants, enumerations)


Study outline: 

 


table of Contents

DataWhale & Golang (three, variables, constants, enumerations)

         Study outline: 

Three, variables, constants, enumerations

to add on:

Value type and reference type

1. Variable

1.1 In short form, use the := assignment operator

2. Go language constants

2.1 iota

2.2 iota usage

3. Enumeration


Three, variables, constants, enumerations

to add on:

Value type and reference type

All basic types like int, float, bool, and string are value types, and variables using these types directly point to values ​​stored in memory:

4.4.2_fig4.1

When using the equal sign  = to assign the value of one variable to another variable, such as:, j = ithe value of i is actually copied in memory:

4.4.2_fig4.2

You can use &i to get the memory address of variable i, for example: 0xf840000040 (the address may be different each time). The value of the value type variable is stored on the stack.

The memory address will vary from machine to machine, and even the same program will have different memory addresses after being executed on different machines. Because each machine may have a different memory layout, and location allocation may also be different.

More complex data usually requires the use of multiple words, and these data are generally stored using reference types.

A reference type variable r1 stores the memory address (number) where the value of r1 is located, or the location of the first word in the memory address.

4.4.2_fig4.3

This memory address is called a pointer, and this pointer is actually stored in another value.

The multiple words pointed to by the pointer of the same reference type can be in consecutive memory addresses (the memory layout is continuous), which is also the most computationally efficient storage form; these words can also be stored in memory, each Each word indicates the memory address of the next word.

When the assignment statement r2 = r1 is used, only the reference (address) is copied.

If the value of r1 is changed, then all references to this value will point to the modified content. In this example, r2 will also be affected.

1. Variable

  • Variables are derived from mathematics and are abstract concepts that can store calculation results or represent values ​​in computer languages.
  • Variables can be accessed by variable name.
  • Variable names in Go language consist of letters, numbers, and underscores, and the first character cannot be a number.
  • The general form of declaring variables is to use the var keyword:
var identifier type

You can also declare multiple variables at once:

var identifier1, identifier2 type

Here is an example to illustrate:

package main
import "fmt"
func main() {
    var a string = "Runoob"
    fmt.Println(a)

    var b, c int = 1, 2
    fmt.Println(b, c)
}

 

Variable declaration:

  • 1. Specify the variable type. If it is not initialized, the value type (including complex64/128) defaults to zero, bool defaults to false, and string defaults to "", "var a *int, var a []int, var a map[string] int, var a chan int, var a func(string) int, var a error // error is the interface "default nil
  • 2. Judge the type based on the value
  • 3. ":=" statement, omit var, note: = a new variable must be declared on the left, otherwise a compilation error will occur, format: v_name := value
  • 4. Multi-variable declaration:
package main
import "fmt"
func main() {

    // 声明一个变量并初始化
    var a = "RUNOOB"
    fmt.Println(a)

    // 没有初始化就为零值
    var b int
    fmt.Println(b)

    // bool 零值为 false
    var c bool
    fmt.Println(c)
}

  • Value type (including complex64/128) is  0

  • Boolean type is  false

  • The string is  "" (empty string)

  • The following types are  nil :
  1. var a * int
  2. var a [] int
  3. var a map[string] int
  4. var a chan int
  5. var a func(string) int
  6. var a error // error is the interface
package main

import "fmt"

func main() {
    var i int
    var f float64
    var b bool
    var s string
    fmt.Printf("%v %v %v %q\n", i, f, b, s)
}

1.1 In short form, use the := assignment operator

We know that the type of the variable can be omitted when the variable is initialized and the system automatically infers it. It is actually a bit redundant to write the var keyword in the declaration statement, so we can abbreviate them as a := 50 or b := false.

The types of a and b (int and bool) will be inferred automatically by the compiler.

This is the preferred form of using variables, but it can only be used in the body of a function, not in the declaration and assignment of global variables. Use the operator: = to efficiently create a new variable, which is called an initialization declaration.

Note:

  • 1. ":=" Assignment operator, efficient creation of new variables, initialization declaration: a := 50 or b := false, the types of a and b (int and bool) will be automatically inferred by the compiler.
  • 2. This is the preferred form of using variables, but it can only be used in the body of a function, not in the declaration and assignment of global variables.
  • 3. In the same code block, we cannot use the initialization declaration again for the variable of the same name, but can assign values;
  • 4. Declaring a local variable but not using it in the same code block will also get a compilation error
  • 5. Global variables can be declared but not used.
  • 6. _ is actually a write-only variable, you cannot get its value. This is because all declared variables must be used in the Go language, but sometimes you do not need to use all the return values ​​from a function.
  • 7. If in the same code block, we cannot use the initialization declaration for the variable with the same name again, for example: a := 20 is not allowed, the compiler will prompt the error no new variables on left side of :=, But a = 20 is ok, because this is to assign a new value to the same variable.
  • 8. If you use it before defining variable a, you will get a compilation error undefined: a.

2. Go language constants

  • A constant is an identifier of a simple value, an amount that will not be modified when the program is running.
  • The data types in constants can only be boolean, numeric (integer, floating-point, and complex) and string types.
  • Constant definition format:

               const identifier [type] = value

  • You can omit the type specifier [type] because the compiler can infer the type of the variable based on the value of the variable.
  • Explicit type definition: const b string = "abc"
  • Implicit type definition: const b = "abc"
  • Multiple declarations of the same type can be abbreviated as:

               const c_name1, c_name2 = value1, value2

Run a simple case:

package main

import "fmt"

func main() {
   const LENGTH int = 10
   const WIDTH int = 5   
   var area int
   const a, b, c = 1, false, "str" //多重赋值

   area = LENGTH * WIDTH
   fmt.Printf("面积为 : %d", area)
   println()
   println(a, b, c)   
}

  • The numbers 0, 1, and 2 represent unknown gender, female, and male, respectively.
  • Constants can use the len(), cap(), unsafe.Sizeof() functions to calculate the value of the expression. In the constant expression, the function must be a built-in function, otherwise it will not compile

2.1 iota

iota, a special constant, can be considered a constant that can be modified by the compiler.

iota will be reset to 0 when the const keyword appears (before the first line inside const), and every new line of constant declaration in const will count iota (iota can be understood as the line index in the const statement block).

iota can be used as an enumeration value:

const (
    a = iota
    b = iota
    c = iota
)

The first iota is equal to 0. Whenever iota is used in a new line, its value is automatically increased by 1; so a=0, b=1, c=2 can be abbreviated as follows:

const (
    a = iota
    b
    c
)

 

2.2 iota usage

iota 用法
实例
package main

import "fmt"

func main() {
    const (
            a = iota   //0
            b          //1
            c          //2
            d = "ha"   //独立值,iota += 1
            e          //"ha"   iota += 1
            f = 100    //iota +=1
            g          //100  iota +=1
            h = iota   //7,恢复计数
            i          //8
    )
    fmt.Println(a,b,c,d,e,f,g,h,i)
}

 

ota means adding 1 automatically from 0, so i=1<<0, j=3<<1 ( <<  means shifting to the left), that is: i=1, j=6, this is no problem, the key is k And l, k=3<<2, l=3<<3 from the output result.

Simply stated:

  • i=1 : shift to the left by 0 bits, and remain unchanged at 1;
  • j=3 : shift 1 bit to the left, it becomes 110 in binary, which is 6;
  • k=3 : Shift left by 2 bits, it becomes binary 1100, which is 12;
  • l=3 : Shift left by 3 bits, it becomes 11000 in binary, that is, 24.

注:<<n==*(2^n)。


3. Enumeration

Enumeration lists the values ​​of the variables one by one, and the variables are limited to the range of the listed values. There is no enumeration of this data type in the Go language, but it can be implemented using const and iota mode

Go language does not provide the definition of enum, we can use const to simulate enumeration types.

package main

import  (
  "fmt"
)

type PolicyType int32

const (
    Policy_MIN      PolicyType = 0 
    Policy_MAX      PolicyType = 1 
    Policy_MID      PolicyType = 2 
    Policy_AVG      PolicyType = 3 
)

func (p PolicyType) String() string {
    switch (p) {
    case Policy_MIN: return "MIN"
    case Policy_MAX: return "MAX"
    case Policy_MID: return "MID"
    case Policy_AVG: return "AVG"
    default:         return "UNKNOWN"
    }
}

func foo(p PolicyType) {
    fmt.Printf("enum value: %v\n", p)
}

func main() {
    foo(Policy_MAX)
}

operation result:

$ go build && ./main 
enum value: MAX

When a variable (especially a method parameter) can only be taken from a small selection set, enumeration should be used. For example, type constants (contract status: "permanent", "temp", "apprentice") or flags ("executing", "delayed execution"), etc.
When using an enumeration to replace an integer, the runtime will check whether the passed parameter is a valid parameter (whether it is in the defined enumeration set) to avoid mistakenly passing in an unusable constant.

Guess you like

Origin blog.csdn.net/adminkeys/article/details/111313387