Notes on golang (2): types, variables and constants

Time:2021-7-9

Basic types

1. List of basic types

Copy codeThe code is as follows:
type         length      explain
bool          one       True / false, the default is false, and non-zero values cannot be regarded as true (no number is used to represent true / false)
byte          one       Uint8 alias
rune          four       Int32 alias. Represents a Unicode point
int/unit             First, the running platform is 32bit / 64bit
int8/uint8   1     -128 ~ 127; 0 ~ 255
int16/uint16 2     -32768 ~ 32767; 0 ~ 65535
int32/uint32 4      – 2.1-2.1 billion, 0-4.2 billion
int64/uint64 8

float32       four      Accurate to 7 decimal places, equivalent to the float of C
float64       eight      Accurate to 15 decimal places, equivalent to the double of C

complex64    8
complex128   16

uintptr             Enough 32-bit, 64 bit integers to hold pointers, pointers (integer type that can hold pointers)
array               Value type, array
struct              Value type, struct
string              Value type, string type, common
slice               Reference types, slicing
map                 Reference type, dictionary
channel             Reference type, channel
interface           Interface type
function            Function type, function

2. Type conversion

Implicit type conversion is not supported, explicit type conversion is required

Conversion only occurs between two compatible types: all types of ints are not allowed to assign values or operate on each other, otherwise errors will occur during compilation

Copy codeThe code is as follows:
<type>(expression)

Examples

Copy codeThe code is as follows:
package main
import “fmt”

func main(){
    a := 0x1234
    b := 1234.56
    c := 256

    fmt.Printf(“%x\n”, uint8(a))
    fmt.Printf(“%d\n”, int(b))
    fmt.Printf(“%f\n”, float64(c))
}

result

Copy codeThe code is as follows:
34
1234
256.000000

3. Type alias

Copy codeThe code is as follows:
type t_str string
var b t_str = “a str”

4. Type default value

Declaration does not assign value, type zero value, non null value, but the default value after declaration

Copy codeThe code is as follows:
bool: false
integers: 0
floats: 0.0
string: “”
pointers,functions,interfaces,slices,channels,maps: nil

Reserved word

Copy codeThe code is as follows:
break      case   chan     const        continue
default    defer  else     fallthrough  for
func       go     goto     if           import
interface  map    package  range        return
select     struct switch   type         var

variable

1. Variable declaration

Copy codeThe code is as follows:
//The first one is to specify the variable type. If the value is not assigned after declaration, the default value will be used
var v_name v_type
v_name = value

//The second is to determine the type of variable according to the value
var v_name = value

//Third, omit var. note: the variable on the left side of = should not be declared, otherwise it will lead to compilation error
v_name := value

e.g.
var a int = 10
var b = 10
c : = 10

Example:

Copy codeThe code is as follows:
package main
var a = 1234
var b string = “hello”
var c bool

func main(){
    println(a, b, c)
}

result:

Copy codeThe code is as follows:
1234 hello false

2. Multivariable declaration:

Copy codeThe code is as follows:
//Multiple variables of the same type are not global variables
var vname1, vname2, vname3 type
vname1, vname2, vname3 = v1, v2, v3

Var vname1, vname2, vname3 = V1, V2, V3 / / is very similar to python. It does not need to display declaration types and infer automatically

Vname1, vname2, vname3: = V1, V2, V3 / / variables appearing on the left of: = should not have been declared, otherwise compilation errors will be caused

//Different types of multiple variables, global variables, local variables can not use this way
var (
    vname1 v_type1
    vname2 v_type2
)

Example:

Copy codeThe code is as follows:
package main

var x, y int
var (   // This can only appear in global variables, not in function bodies
    a int
    b bool
)

var c, d int = 1, 2
var e, f = 123, “hello”

//This non declarative format can only appear in the body of a function
//g, h := 123, “hello”

func main(){
    g, h := 123, “hello”
    println(x, y, a, b, c, d, e, f, g, h)
}

result:

Copy codeThe code is as follows:
0 0 0 false 1 2 123 hello 123 hello

be careful:

A. In multivariable assignment, the values of all variables on the left side will be calculated first and then assigned

Copy codeThe code is as follows:
    i := 0
    i, l[i] = 1, 2
    //get i = 1, l[0] = 2

    sc[0], sc[0] = 1, 2
    //get sc[0] = 2

B. Trash can_

Copy codeThe code is as follows:
    func test()(int, string) {
        return 123, “abc”
    }

    a, _ := test()

C. Variables that have been declared but not used will report errors at the compile time, which is more stringent than python

constant

Constants can be characters, strings, Booleans or numbers

Constant assignment is compile time behavior

1. Constant declaration

A value that can be determined at compile time and cannot be changed at run time
Constants can be defined as numeric, Boolean, or string types

Copy codeThe code is as follows:
const constantName = value
const Pi float32 = 3.1415926

const c_name [type] = value
const c_name1, c_name2 = value1, value2
const (
    c_name1 = vluae1
    c_name2 = value2
)

=On the right side, it must be a constant or a constant expression. If a function is used, it must be a built-in function (compile time behavior)

const i = 10000

explain:

Copy codeThe code is as follows:
A. Constants must be number (char / integer / float / complex), string and bool that can be determined at compile time

B. When defining a constant array, if no initialization value is provided, it means that it is exactly the same as the upstream constant type and value

    const (
        a = “abc”
        b
    )
    // Then B = “ABC”

C. Constant can use len (), cap (), unsafe. Sizeof () constant to evaluate the value of expression   In a constant expression, the function must be built-in, otherwise it will not compile

    package main

    import “unsafe”
    const (
        a = “abc”
        b = len(a)
        c = unsafe.Sizeof(a)
    )

    func main(){
        println(a, b, c)
    }

result:     abc 3 16

enumeration

Iota, a special constant, can be considered as a constant that can be modified by the compiler

When each const keyword appears, it is reset to 0, and then before the next const keyword appears, the number represented by iota will automatically increase by 1 every time it appears

If no initial value is provided, the expression on the previous line is used

1. Statement:

Iota generates an auto growing enumeration value starting from 0, which means that there is one more enumeration value, iota + = 1, regardless of whether it is used or not

Basic grammar

Copy codeThe code is as follows:
const (
    a = 1
    b = 2
)

const (
    a = iota //0
    b  //1
    c  //2
)

const (
    _ = iota
    a    //1
    b    //2
)

Iota usage

Copy codeThe code is as follows:
func main() {
    const (
            a = iota  //0
            b   //1
            c   //2
            d = “ha”   // Independent value, iota + = 1
            e    //”ha”   iota += 1
            f = 100    //iota +=1
            g     //100  iota +=1
            h = iota   // 7, recovery count
            i      //8
    )

}

const (
    x = iota // 0
    y = iota // 1
    z = iota // 2
    W / / omitted. The default value is the same as before    W = iota, i.e. 3
)
Const v = iota / / if const keyword is encountered, iota will be reset

Note: the number of variables in each row must be consistent with const (a, B = iota, iota C, D, e, f)

Copy codeThe code is as follows:
func main() {
    println(A,B,C,D,E,F)
}

//Results: 0 01 1 2 2    【 [respective growth]

operator

The go operator is all left to right

Operator overloading is not supported

Copy codeThe code is as follows:
priority     operator                         explain
  high    * / % << >> & &^( AND NOT)
       + – ! ^
       == != < <= > >=
       <-                             Channel operator
       &&
  low    ||

In go, + + — is a statement, not an expression

Copy codeThe code is as follows:
package main

func main(){
    i := 1
    i ++
    println(i)

    b := i
    println(b)

    //syntax error: unexpected ++, expecting semicolon or newline or }
    //c := i++
    // This means that + + / – – cannot appear to the right of the equal sign
}

Pointer

Go keeps the pointer, and * t represents the pointer type corresponding to t

If the package name is included, it should be *. T

The symbol ‘*’ representing a pointer type is always placed with the type, not next to the variable name

Also supports pointer * * t

1. Statement

Copy codeThe code is as follows:
var a, b *int

2. Description

Copy codeThe code is as follows:
Operator & takes the variable address and uses * to indirectly access the target object through pointer variables
The default value is nil and there is no null constant
Pointer operation is not supported, and ‘- >’ is not supported. Direct ‘.’ selector operates pointer target object members
You can convert between unsafe. Pointer and any type pointer
You can convert unsafe. Pointer to uintptr, and then do pointer operation in disguised form. Uintptr can be converted to integer

3. Examples

Copy codeThe code is as follows:
package main
import “fmt”

type User struct {
    Id int
    Name string
}
func main(){
    i := 100
    var p *int = &i   // Take address

println(*p)    // Value

    up := &User{1, “Jack”}
    up.Id = 100   // Direct access only for members
    fmt.Println(up)

    u2 := *up   // Copy Object
    u2.Name = “Tom”
    fmt.Println(up, u2)
}

4

Copy codeThe code is as follows:
100
&{100 Jack}
&{100 Jack} {100 Tom}

Group statement

Copy codeThe code is as follows:
import (
    “fmt”
    “os”
)

const (
    i = 100   // The first line must have a constant expression
    pi = 3.1415
)

var (   // Global variables are available, but not in function bodies
    i int
    pi float32
)

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]