SoFunction
Updated on 2025-03-03

Golang study notes (II): types, variables, constants

Basic Type

1. Basic type list

Copy the codeThe code is as follows:

Type        Length     Description
bool                                                                                                                              �
byte                  uint8 alias
rune                                                              � Represents a unicode code point
int/unit
int8/uint8   1     -128 ~ 127; 0 ~ 255
int16/uint16 2     -32768 ~ 32767; 0 ~ 65535
int32/uint32 4    -2.1 billion ~ 2.1 billion ~ 4.2 billion ~ 4.2 billion
int64/uint64 8

float32       4
float64       8

complex64    8
complex128   16

uintptr
array
struct                                                              �
string
slice
map
channel                           Reference type, channel
interface
function

2. Type conversion

Implicit type conversion is not supported, explicit type conversion must be performed

The conversion only occurs between two mutually compatible types: various ints do not allow assignment or operations to each other, otherwise an error will be reported during compilation.

Copy the codeThe code is as follows:

<type>(expression)

Example
Copy the codeThe code is as follows:

package main
import "fmt"

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

    ("%x\n", uint8(a))
    ("%d\n", int(b))
    ("%f\n", float64(c))
}


result
Copy the codeThe code is as follows:

34
1234
256.000000

3. Type alias

Copy the codeThe code is as follows:

type t_str string
var b t_str = "a str"

4. Type default value

Declares no assignment, type zero value, non-null value, but the default value after declaration

Copy the codeThe code is as follows:

bool: false
integers: 0
floats: 0.0
string: ""
pointers,functions,interfaces,slices,channels,maps: nil

Reserved words

Copy the 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 the codeThe code is as follows:

//The first type is to specify the variable type. If the value is not assigned after declaration, use the default value.
var v_name v_type
v_name = value

//The second type, determine the variable type by yourself based on the value
var v_name = value

//The third type is omitted, note that the variable on the left should not have been declared, otherwise it will cause a compilation error.
v_name := value

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

Example:

Copy the 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 the codeThe code is as follows:

1234 hello false

2. Multivariate declaration:

Copy the codeThe code is as follows:

// Multiple variables of the same type, non-global variables
var vname1, vname2, vname3 type
vname1, vname2, vname3 = v1, v2, v3

var vname1, vname2, vname3 = v1, v2, v3 //It is very similar to python, and does not need to display the declaration type, and it is automatically inferred

vname1, vname2, vname3 := v1, v2, v3 //The variables appearing on:= should not have been declared, otherwise it will cause a compilation error


//There are multiple variables of different types, and global variables cannot be used in this way.
var (
    vname1 v_type1
    vname2 v_type2
)


Example:
Copy the codeThe code is as follows:

package main

var x, y int
var (  //This type of thing can only appear in global variables and is not supported in the function body
    a int
    b bool
)

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

//This type of non-declaration format can only appear in the function body
//g, h := 123, "hello"

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


result:
Copy the codeThe code is as follows:

0 0 0 false 1 2 123 hello 123 hello

Notice:

A. When multi-variable assignment, the values ​​of all left variables will be calculated first, and then the assignment will be performed.

Copy the 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 the codeThe code is as follows:

    func test()(int, string) {
        return 123, "abc"
    }

    a, _ := test()

C. Variables that have been declared but are not used will report an error during the compilation stage, which is more stringent than Python.

constant

Constants can be characters, strings, booleans, or numbers

Constant assignment is the behavior during the compilation period

1. Constant declaration

The value that can be determined during the compilation stage, and the value cannot be changed during runtime
Constants can be defined as numerical, boolean or string types.

Copy the 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 constant expression. If a function is used, it must be a built-in function (compilation period behavior)

const i = 10000

illustrate:

Copy the codeThe code is as follows:

A. Constants must be Number(char/integer/float/complex), String and bool that can be determined during the compile period.

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

    const (
        a = "abc"
        b
    )
//Then b = "abc"

C. Constants can use len(), cap(), and () constants to calculate the value of an expression. In a constant expression, the function must be a built-in function, otherwise it will not be compiled.

    package main

    import "unsafe"
    const (
        a = "abc"
        b = len(a)
        c = (a)
    )

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


Results: abc 3 16

enumerate

iota, a special constant, can be considered 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 appears, every time the iota appears, the number it represents will automatically increase by 1

If no initial value is provided, it means that the expression from the previous line is used.

1. Statement:

iota generates an automatically growing enum value starting from 0, meaning that one more enum value is, iota+=1, regardless of whether it is used or not.

Basic syntax

Copy the 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 the 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 is the same as before. w = iota, that is, 3
)
const v = iota //I encounter the const keyword, iota resets

Note: The number of variables per row must be consistent const ( A, B = iota, iota C, D E, F )

Copy the codeThe code is as follows:

func main() {
    println(A,B,C,D,E,F)
}

//Result: 0 0 1 1 2 2   【Each person grows】

Operators

All Go operators are combined from left to right

Operator overloading is not supported

Copy the codeThe code is as follows:

Priority Operator
High   * / % << >> & &^(AND NOT)
       + - ! ^
       == != < <= > >=
<-                                                                                                                              �
       &&
Low   ||

In go, ++ -- is a statement, not an expression
Copy the 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++
// Meaning, ++/-- cannot appear on the right side of the equal sign
}

pointer

Go retains pointers, *T represents the pointer type corresponding to T.

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

Symbols '*' representing pointer type are always placed with the type, not next to the variable name

Pointers that also support pointers**T

1. Statement

Copy the codeThe code is as follows:

var a, b *int

2. Explanation
Copy the codeThe code is as follows:

Operator & get variable address, use * to indirectly access the target object through pointer variables
The default value is nil, no NULL constant
Pointer operation is not supported, '->' budget blessing, directly '.' selector operates pointer target object members
Can be converted between pointers of any type
You can convert it to uintptr and then do pointer operation in disguise. Uintptr can be converted to integers

3. Example

Copy the codeThe code is as follows:

package main
import "fmt"

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

println(*p)   //Get the value


    up := &User{1, "Jack"}
= 100 //Select directly only for the members
    (up)

u2 := *up  //Copy the object
    = "Tom"
    (up, u2)
}

4. Results:

Copy the codeThe code is as follows:

100
&{100 Jack}
&{100 Jack} {100 Tom}

Grouping Statement
Copy the 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, not supported in the function body
    i int
    pi float32
)