Go language learning note for C programer

This is a Go language learning note for C programer.

You can use this note to quickly learn Go.

1. Grammar

1.1. Constant

1
Const var [TYPE] = xxx

Const can not specify the type, it will be automatically judged at compile time.

Define multiple constants that can be written as one line

1
Const Jan, Feb, Mar, App = 1, 2, 3, 4

Can also take the following form

1
2
3
4
Const (
Jan, Feb = 1, 2
Mar, App = 3, 4
)

Combined enumeration

1
2
3
4
5
Const (
Jan = 1
Feb = 2
// ...
)

If the enumeration is in the form of 0 1 2 3, you can use iota

1
2
3
4
5
Const (
Jan = iota
Feb
Mar
)

Constants have no length limit, such as

1
Const a = 1.2321390234804823094802348238402340234092384204

1.2. Variables

Define the variable keyword as var format as

1
2
3
4
Var name [TYPE] [= xxx]
Such as:
Var a int
Var b float = 19.8

All memory is initialized in Go, so defining variables can not be assigned initial values. If the initial value is not assigned, the initial value of the corresponding type is assigned.

  • int -> 0
  • float -> 0.0
  • bool -> false
  • string -> ‘’
  • pointer -> nil

Note that it is an error to just declare a variable but not compile it with a variable. This is the embodiment of the idea that the go language does not need to be defined. But one exception is that global variables can be declared but not used

If the compiler can determine the variable type based on the initial value when compiling, you can not specify the variable type, such as:

1
2
3
Var a = 100
Var hello = 'nihao'
Var HOME = os.Getenv("HOME")

But if the compiler can’t judge the format, it will report an error, such as

1
Var a // no initial value or no specified type

As with constants, multiple variable declarations can be written as one line or as one-time assignments.

1
2
3
Var a, b, c, d int
Var a, b, c, d = 1, 2, 3, 4
// abcd is int type

There is also a simple way to declare variables :=

1
2
3
a := 1
b := false
Name := 'bob'

Equivalent to var a = 1

Of course, the declaration + assignment in a row is also easy to accomplish.

1
a, b, c, d := 1, 2, 3, 4

If it has been declared, it can be batch-valued in a row like python.

1
a, b, c, d = 200, 201, 202, 203

This is similar to python’s unpack, called parallel assignment in go, which makes it easy to exchange variable values.

1
2
3
4
5
a, b := 100, 200
a, b = b, a // a=200, b=100

// can also unpack the return value of the function
a, b = func1()

1.2.1. _ variable

Go has a special variable _, which can be assigned the same value as an ordinary variable, but can’t get the value (that is, it can only be written, not readable)

The purpose of this variable is to discard some unneeded variables (because the variable definition in go must be used, otherwise it will report an error, but in fact some variables will not be used, such as the return value of the function)

Such as:

1
2
_, b = 100, 200
_, b = func1()

1.2.2. init() function

Go has a special function called init(), which cannot be called manually. It will be called automatically after the package has finished initializing. It can be used to initialize global variables.

The execution priority of this function is very high, even before main(), so one possible use is to verify or repair the data before starting the program to ensure the correctness of the program state.

1
2
3
4
5
6
7
8
9
Package trans

Import "math"

Var Pi float64

Func init() {
Pi = 4 * math.Atan(1) // init() function computes Pi
}

Or determine the type of operating system

1
2
3
4
5
6
7
Func init() {
If runtime.GOOS == "windows" {
Prompt = fmt.Sprintf(prompt, "Ctrl+Z, Enter")
} else { //Unix-like
Prompt = fmt.Sprintf(prompt, "Ctrl+D")
}
}

1.3. Pointer

1.3.1. Addressing &

Use & to get the memory address corresponding to the variable

1
2
a := 100
fmt.Print( &a )

1.4. Types and operations

Go is a strongly typed language that does not allow any form of implicit type conversion, such as binary operators that only allow two variables of the same type to be evaluated

**Note: Int32 unt64 is also not allowed to perform operations without conversion.

But the constant limit is loose, such as:

1
2
Var a int64 = 20
a = a + 10

Because 10 is a constant written in the code, it will not compile error

1.4.1. bool type and operation

Go uses false true as the result of the bool operation
The logical connection symbol is the same as c:

  • && versus
  • || or
  • !

The comparison also has

  • == != >
    1
    2
    3
    4

    As with Python, when connecting multiple logical operations with `&&` `||`, if a condition can already produce the result of the entire operation, there is no need to calculate the following expression, such as:
    ```go
    1<100 || 2> 400

Because 1<100 is true, the result of the expression is true, and the following 2>400 will not be executed.

1.4.2. Number Types and Operations

Integer:

  • int uint uintptr.

    These types are architecture-based, that is, the corresponding number of bits is automatically used depending on the environment in which they are run. On 32-bit systems, int uses int32, on 64-bit systems, int uses int64. uintptr is long enough to hold a pointer.

  • int8 int16 int32 int64 uint8 uint16 uint32 uint64

    These are independent of the architecture and have a certain length.

  • byte

    byte is actually int8, which is used to represent ASCII characters.

plural:

Go native support plural

  • complex64 (32-bit real number + 32-bit imaginary number)
  • complex128 (64-bit real number + 64-bit imaginary number)

    The plural definition iI in the form of real + imi represents the root number -1:

    1
    Var c1 complex128 = 1 + 10i

    To get the imaginary part of the real number of imaginary numbers, use real() imag()

floating point:

  • float32 (accurate to 7 decimal places)
  • float64 (accurate to 15 decimal places)

    Because of the accuracy problem, be careful when comparing decimals

    Also try to use float64 because the math package is used for this

    divided by 0
    Dividing an integer by 0 will cause a crash or the compilation will fail, and the floating point divided by 0 will get +∞
    Use +Inf for program

1.4.2.1. Operation

Arithmetic operator: + - * / %

At the same time, like c, it also supports: ++ -- += -= *= /= %=

note:

++ -- is self-increase and decrement, only acts on the variable itself, cannot be assigned, such as:

1
Var a = i++

1.4.3. Character type

1
Var a byte = 'A'

Like c, go’s character type byte is actually just an alias for int8 (typeof byte int8)

So you can use the corresponding ASCII value directly

1
2
3
4
Var a byte = 32
Var b int8 = 33
Var c byte = '\x41' // \x followed by 2 digits expressed as hexadecimal value
Var d byte = '\x377' // \x followed by a 3-digit number as an octal value

1.4.3.1. Unicode( UTF-8 )

Go native support for unicode, starting with \u \U

Because unicode requires multiple bytes to represent characters, the short one may be 2 bytes, the long pit is 4 bytes, corresponding to the specific int type is int16 int32.

Which type is used specifically, by \u \U, \u is 2 bytes (int16), \U is 4 bytes (int32)

1
2
Var ch int = '\u0041' //2 bytes unicode
Var ch2 int = '\U00101234' //4 bytes unicode

unicode output

  • %c output unicode characters
  • %d %v outputs the decimal value corresponding to the unicode code
  • %X output hexadecimal unicode code
  • %U outputs unicode code in U+xxxx format

unicode package

There are some convenient methods in the unicode package:

  • Is it a letter: unicode.IsLetter(ch)
  • Is it a number: unicode.IsDigit(ch)
  • Is it a blank symbol: unicode.IsSpace(ch)

1.4.4. In hexadecimal

Same as c

  • 0 starts with octal
  • 0x starts with hexadecimal
  • e 10 nth power (1e5 = 1*10^5)

1.4.5. Bit operation

Can only be used for integers and needs to be equal in length.

  • Bit & &

    And& is similar to logical operation 1 is ture 0 is false

  • bit or |

    And logical operations || Similar 1 is true 0 is false

  • Bit XOR or ^

    The equality of the two results is 0, not equal to 1, such as:

    1
    2
    1 ^ 1 = 0
    1 ^ 0 = 1
  • Bit clear &^

    The value at the specified location is set to 0

  • Bit left shift << Usage: a << n

    Indicates that a shifts the n bit to the left, the overflow is discarded, and the insufficient portion is filled with `0’.

    Use of left shift

    Shift one bit by a considerable number of times by 2^1, and shifting the n bit to the left is equivalent to multiplying the number by 2^n.

    The left shift operation speed is faster than the simple multiplication method, so when calculating a*2^n, it can be written as a << n

    Because of this feature of left shift, you can quickly calculate the specific number of bytes of KB MB GB and so on:

    • 1KB = 1 * 2^10 can be written as 1 << 10
    • 1MB = 1 * 2^20 can be written as 1 << 20
    • 1GB = 1 * 2^30 can be written as 1 << 30
    • TB PB and so on
  • Bit right shift >> Usage: a >> n

    Contrary to the left shift, shift n bits to the right. The same is the overflow part is discarded, the insufficient part is filled with 0
    The meaning is also opposite to the left shift. The left shift n bits is a*2^n, and the right shift is a/2^n.

1.4.6. Display type conversion

By calling the method of the corresponding type, int32() int64() etc.
Such as:

1
2
3
4
5
6
7
8
9
10
Package main

Import "fmt"

Func main() {
Var n int16 = 34
Var m int32

m = int32(n)
}

Type conversion when defining:

1
a := uint64(0)

1.4.7. Operator precedence

Priority Operator
7 ^ !
6 * / % << >> & &^
5 + - ^
4 == != < <= >= >
3 <-
2 &&
1 ` `

2. String

Like c, the string of go is also an array of characters.

Also supports transfer of strings \n \r

However, unlike c\c++, the go string does not end with \0, but ends directly (this is similar to a dynamic language like python, the empty string is "")

2.1. Comparison of strings

== > … etc. The operation is to achieve string comparison by byte comparison in memory.

2.2. String length

String length (bytes) can be obtained by len()

Unicode can have 1~4 bytes for a character. If you want to count the number of characters in utf-8, use utf8.RuneCountInString() in theunicode/utf-8` package.

2.3. String index value

Because the string of go is an array, you can get the character of the string by means of an array.

1
Str[0]

2.4. String splicing +, +=

Like python, go makes it easy to stitch strings.

1
2
Str := "hello" + " world"
Str += "!"

note
Although the + splicing string is convenient, the efficiency is not very high. If you are splicing strings in a loop and have efficiency requirements, you can use the following methods:

  1. strings.Join()
  2. Or use the buffer string bytes.Buffer like c

2.5. strings package

The strings package contains some basic operations on strings.

  1. Does it start with xxx

    strings.HasPrefix(s, prefix)

  2. Whether to end with xxx

    strings.HasSuffix(s, suffix)

  3. Whether to include

    strings.Contains(s, substr)

  4. Find the substring position

    strings.Index(s, substr). This finds the location where it first appears. Return -1 means not included
    strings.LastIndex(s, substr). This finds the last occurrence of the location. Return -1 means not included

pointer

Like c, go can also define pointers, 32-bit system pointers are 32 bits long, and 64-bit systems are 64 bits.

But the pointer of go does not allow pointer arithmetic (such as ptr+1, ptr+2, will report an error. This is a bit like python, java pass reference)

1
2
Var p *int
Var p*int // This is also legal, but it is not recommended, because in complex expressions, it is easy to be mistaken for multiplication

Addressing operation &

Like c, you can get the memory address of a variable &a by &:

1
2
Var a = 100
Var bp *int = &a

note

Cannot get constant or text address

Value operation *

Like c, use * in front of the pointer to get the pointer to the data in memory.

1
2
3
Var a = 100
Var bp *int = &a
fmp.Print(*bp) // output 100

By the *bp operation, the value of the corresponding a variable can be changed.

Contral

Judging

if else

1
2
3
4
5
6
7
8
9
10
11
If condition {
// The () symbol on both sides of the judgment condition can be omitted. If the condition is more complicated, it can be taken.

}else if condition {
// else must be with the brackets} consent level,
// }
// else{
/ / The above is not allowed by the go, the compiler will report an error
}else{

}

Or go has a way of writing, you can run an initialization statement first, and then judge, such as:

1
2
3
If initialized; condition {
// The variable defined in the initialization is a local variable, only in the entire if code block (including else)
}

This can be used to get a one-time initial value.

1
2
3
4
5
6
7
If value := func1(data); value > 100 {
// The value here is a local variable
}
// or
If value, ok := readData(); ok{
Value // operation on value
}

*if some useful ways

  1. Determine if the string is empty if str == "" or if len(str)==0

switch

Same as c‘s `switch’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Switch variable {
Case value 1:
// Unlike c, go will exit the entire switch block after executing a case.
// If you want to continue with c, you can use fallthrouth to execute to the next case.
Fallthrough
//The code inside the switch does not need to use curly braces

Case value 2: // If the code has only one line, it can be written like this case like this
Case value 3, value 4, value 5:
/ / Can test multiple values ​​like this
// Manually jump out of the entire switch and use break like c
Break
Default:
// The position of defalut is actually indifferent. It doesn't matter where it is placed. But it is best to put the following
}

There is also a way to write switch, which is to provide variables for judgment. All judgments are done in case.

1
2
3
4
5
6
7
8
9
10
Switch {
Case value <0:
// code
Case value == 0:
// code
Case value > 0:
//code
Default:
//code
}

This is actually the same as if else if else, but when there are a lot of else if conditions, the switch is more readable.

switch The third way to write an initialization statement like if

1
2
3
4
5
6
7
8
Switch initialization {
Case val1:
...
Case val2:
...
Default:
...
}

for loop

The loop of go is only for

普通 Usage: Counter iteration

This is very similar to the for usage of c:

1
2
3
For i:=0; i<10; i++{

}

But go also supports multiple counters

1
2
3
For i, j:=0,N; i<j, i,j=i+1, j-1{

}

###类while usage
When you don’t need to initialize variables, you can write for like you would write while

1
2
3
4
5
6
i := 0
For i<100 {
// Of course, like c, it is written as: for ;i<100; {} is also possible
// However, this method will be corrected by gofmt to for i<100
i++
}

Infinite loop

1
2
3
4
5
For i:=0;;i++{
If i>100{
Break
}
}

In this way, there is no infinite loop, and it is necessary to judge when the program is launched inside the program.

Of course, it is okay to write for true{} directly. However, writing ‘for {}directly at this time is the same meaning, equivalent tofor true{}`.

for range

It’s similar to looping on an iterator. But the difference is that you can get both idx and value

Note: The value obtained for range is a copy of the corresponding value! Not a reference! Modifying the value cannot change the original value!

Written as:

1
2
3
For idx, value := range ITEMS {

}

The more common usage is to iterate through the loop string (go’s string is unicode, but it can handle unicode characters correctly by range iteration)

1
2
3
For idx, char := range "Hello" {
fmt.Println(idx, char) // Note that the direct print char output is the int value of the string
}

goto

Never try to use goto! Because goto proved to be extremely bad code habits!

Like c, goto can jump to the desired tag: note that goto can jump within the same function

function

  • go is a compiled language, all functions are automatically found at compile time, so the definition and calling order of the function does not matter.
  • go language does not allow function overloading (because the matching type procedure for function overloading consumes performance)
  • Unlike c c# and other languages, the go function supports returning multiple values. For example, a function that sends a message can return a message content object and a flag indicating whether the transmission was successful.
  • go language does not provide default values ​​for formal parameters like python, and must provide the corresponding value each time.
    Function declaration
    1
    2
    3
    Func function name (parameter list) (return value type list) {
    // function body
    }

example

1
2
3
4
5
6
7
8
9
10
11
Func add(a, b int) (int){
Return a + b
}

Func add_2(a, b int)(int, int, int){
Return a, b, a+b
}

Func fun1(a int, _ int) {
// Function parameters can also be used _
}

If the return value list has only one return value, () can be omitted

If there is no return value, the return value list can be omitted

The function’s return value list can also be named like a formal parameter. The named variable is given the initial value. If you call return, there is no explicit return variable, it will automatically return the corresponding variable.

1
2
3
4
5
6
Func add(a, b int)( return_a, return_b, result int){
Return_a = a
Return_b = b
Result = a+b
Return
}

If you want to return multiple return values, you can use this method to make the reading point clearer.

Passing values ​​and passing references

Like c, go passes the default value (that is, copy)

However, when a function is called, reference types such as slices, maps, interfaces, and channels are passed by reference by default (even if the pointer is not explicitly pointed out).

The pass reference is actually the memory address of the passed variable. The formal parameter defined by the function needs to receive the pointer type of the corresponding format. The operation data is also the same as the pointer:

1
2
3
Func multiply(a, b int, reply *int) {
*reply = a * b
}

Calling this function is also a pass pointer:

1
2
Var reply *int
Multiply(10, 5, &reply)

variable length parameter

Wait for the array part to read and look back

defer

Defer is a bit like some language ‘finnaly`

defer can register some operations. When the function’s return is called**, these operations will be executed. The common use is to close the file handle and so on.

The mechanism of defer is similar to the registration mechanism, so the location of defer in the function does not matter.

defer can be used multiple times in the same function, the execution order is the same as the stack, last in, first out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Func func1(){
i := 0
Defer close_file()
i++
Retrun
}

Func func2(){
i := 0
Defer close_file1()
Defer close_file2()
// return, execute in the order of close_file2() -> close_file1()
i++
Retrun
}

defer only supports one line. If you want to execute multiple statements, you can use anonymous functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Defer func() {
log.Printf("func1(%q) = %d, %v", s, n, err)
log.Printf("over")
}()
```

**defer application in debugging: enter, return tracking**

Another common use of `defer` is to track the leaving function.
```go
Func leave(s string){ fmt.Println("Leave function: ",s)}
Func enter(s string){ fmt.Println("You entered the function: ", s)}
Func func1(){
Enter("func1")
Defer leave("func1")
// some operations
}

For example, if you write “enter”, you can write the above content more concisely:

1
2
3
4
Func enter(s string) string{
fmt.Println("You entered the function: ", s)
Return s
}

In this way, entry and registration can be simplified to

1
Defer leave( enter("func1") )

defer application in debugging: output record parameters and return value

The same reason~

recursion

Don’t like recursion~ look again

Callback (callback)

Passing a function as a parameter to another function call is called callback (callback)

The formal parameter of the receiving function, the type uses func (parameter list) to return the listrepresentation, such as

1
2
3
Func callback( f func(int, int) int ){
Return f(1, 2)
}

The call is also very simple, just pass in the function name directly into it:

1
2
3
4
Func A(a, b int) int{
Return a+b
}
Callback( A )

An example of callback is the IndexFunc in the string package.
The definition of IndexFunc is:

1
2
3
Func IndexFunc(s string, f func(c int) bool) int {
//... internally get the characters of string, then call f(c) to get the corresponding result
}

So just write a judgment function with the corresponding formal parameters and return value:

1
2
3
4
5
6
Func func1(c int) bool{
If c=='A'{
Return true
}
Return false
}

Anonymous function

Functions without names are called anonymous functions. as follows:

1
2
3
Func (i int) int {
Return i*2
}

Anonymous functions cannot exist alone, otherwise compilation errors will be reported, but anonymous functions can be called directly.

By writing parentheses to the right of the braces

1
2
3
4
a := func (i int) int {
Return i*2
}(10)
// Here is the formal parameter 10, and the function return value is assigned to the variable a

An anonymous function can also be assigned to a variable, after which the variable can be called like a function.

1
2
3
4
5
Func1 := func (i int) int {
Return i*2
}

a := func1(100)

Closure

Since an anonymous function can be assigned to a variable, it can naturally be returned as the return value of another function.

One usage is to pass in different variables, use another function to generate new functions with different functions and return them as return values.

This function that returns a function is called a factory function.

As follows, it is a factory function that generates different suffixes:

1
2
3
4
5
6
7
8
9
Func MakeAddSuffix(suffix string) func(string) string {

Return func(name string) string {
If !strings.HasSuffix(name, suffix) {
Return name + suffix
}
Return name
}
}

Usage is as follows

1
2
addBmpSuffix := MakeAddSuffix(".bmp")
Newfilename = addBmpSuffix("testfile") // newfilename = 'testfile.bmp'

The returned function directly uses the variable suffix in the MakeAddSuffix function, which is called a closure.

#Array and slice

Array

The length of the array is deterministic, the length of the array must be constant

Each element is initialized to the initial value of the corresponding type when the array is defined

Array definition and initialization:

1
2
Var array1 [10]int
// only defined, initialized by type defaults

If you want to initialize when defining, use the form 3’int{1, 3, 5}.[3]int{1, 3, 5}` returns an array of length 3, content 1, 2, 3, which can be assigned to a variable:

1
2
3
4
5
6
7
8
/ / Define simultaneous initialization
Var arrayAge = [5]int{19,20,21,22,23} // known length is 5, all initialized
Var arrayAge = [5]int{19} // length 5, only initialize the first one
Var arrayAge = [...]int{19,20,21,22,23} //Define an array of length 5 and initialize all

Var arrayAge = [5]int{0:19, 4:23} // Specify values ​​only for [0] and [4]

Var arrayAgePtr = new([10]int) // This is similar to the way c++ is defined, but note that this method returns not the value of the array, but a pointer to the array.

Like c, the array starts with 0 and the following index value

Different from c

  • If the reference is outside the length range, the compiler will report an error or throw an error when it runs.
  • The array in go is a value, not a pointer to a memory like c
  • The type of the array is not followed by member variables. For example, [10]int and [5]int are different array types.

Array pass value

The array in go is a value, not a pointer to a piece of memory like c

So, when you assign an array from one variable to another, a copy occurs, as follows:

1
2
3
4
5
6
Array1 := [4]int
Array2 := array1
Array2[0] = 100

// array1 [0 0 0 0]
// array2 [100 0 0 0]

If you want to modify the value of an array, use the address operator &:

1
2
3
4
5
6
Array1 := [4]int
Array2 := &array1
Array2[0] = 100

// array1 &[0 0 0 0]
// array2 &[100 0 0 0]

note

Because of the nature of the go array, the function parameter is also a copy of the received array. If you want to change the array, you need to define the parameter like the receive pointer:

1
2
3
Func func1(array1 *[10]int){
// ...
}

But in fact go is not commonly used this way, for arrays such things, go has a more flexible slice to perform the corresponding operations instead of arrays.

Array Traversal

Since the array traversal is using for

1
2
3
4
// General way of writing
For i:=0; i<len(array1); i++{
Array1[i] //.....
}

1
2
3
4
5
/ / Use for range 
For idx, value := range array1 {
Value // the value of for range is just a copy, the original value cannot be modified, so it is best to use idx
Array1[idx]
}

Array application: vector

Geometric points (or mathematical vectors) are a classic example of using arrays. To simplify the code you usually use an alias:

1
2
Type Vector3D [3]float32
Var vec Vector3D

Multidimensional Arrays

The same feeling as c:

1
2
Var a [2][2]int
Var a = [2][2]int{ {1,2}, {4,5} }

Slice

The go slice concept is greatly influenced by python, which is very similar to the python slice.

But the difference is that the go slice is a reference to the original array, and python is a copy.

So if you want to pass the array and modify it in go, it is best to pass the slice of this array directly.

Slice type

[10]int This is an array type

If there is no length, it is the type of slice: []TYPE , such as: []int, []string

Creating a slice

The following creates an empty slice, nil, with a length of 0, which can be assigned to any slice of type []int

1
2
/ / Directly define an empty slice variable slice of type [] int
Var slice []int

The following creates an array and puts a slice at the same time:

1
2
// First create an array of [5]ints, then return a slice pointing to this array
Slice := []int{1,2,3,4,5}

The following creates a slice, slice1 slice length is end-start (3-1=2), contains the data of the start position, but does not contain the data of the end position.

The second slice2 contains the entire array.

1
2
3
4
// Create a slice from an array
Var array1 [5]int
Slice1 := array1[1:3] // Create a slice of type []int
Slice2 := array1[:] // start does not write to start, end does not write to end

Because the slice contains start without the end feature, it makes:

1
Array1 == ( array1[:i] + array1[i:] )

Let’s create a slice with make() below.

The make() creation slice is make(TYPE, len, cap ). The principle is to create an array and then return the slice created from this array.

Note: make can only be used to generate slice, map, channel. And new is used to create all value types (array, structure, int, etc.), and new returns pointer.

1
2
Slice3 = make([]int, 50, 100)
// First create an array of length 100, then return the slice of [0:50] to slice3

Sliced ​​capacity cap and slice recombination reslice

cap refers to the length of the start position of the slice, to the total length of the end position of the original array. Such as:
var array1 [10]int slice := array[1:3] , the length of slice slice1 is 3-1=2, capacity(cap) is original array length 10 - slice start Position 1 = 9

Since the capacity' of the slice is larger than theslice length, the aboveslice1can be expanded. This is different from the slice ofpython`:

The slice1 above is 2, which points to the [1] [2] position of the original array.

Then change the length of the slice with the following code:

1
2
Slice2 = slice1[0:1]
Slice1 = slice1[0:3]

The new slice slice1 points to the [1] [2] [3] position of the original array

slice2 is reduced to [1]

Not only can you change the slice’s end to expand, but you can also change the start to change the position:

1
Slice1 := slice[1:3]

Slice1 changes from the original [1] [2] to the `[2] [3] pointing to the original array.

3. Basic functions

3.1. Print Println Printf Sprintf

Println will automatically bring \n at the end, Print will not
If you want to use %d %f for formatted output like C, use Printf.

1
fmt.Printf("Hello, %v, a is %v", name, a)

%v can automatically call the corresponding formatted output mode according to the variable type
You can manually specify %d %f, etc.

Sprintf returns the string as a function return value, not output

Specific list

  • %v automatically calls the output mode of the corresponding format
  • %d integer, if you want to specify the length, use %2d similar to c
  • %x %X hex
  • %g floats retain decimals like c, %n.2g
  • %f %e floating point number (the latter is output in the form of e)

3.2. Random number

The rand package implements the generation of pseudo-random numbers.

  • You can use the Seed(value) function to provide a seed for generating pseudo-random numbers.
  • The function rand.Intn returns a pseudo-random number between [0, n)
  • The functions rand.Float32 and rand.Float64 return pseudo-random numbers between [0.0, 1.0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Package main
Import (
"fmt"
"math/rand"
"time"
)

Func main() {
For i := 0; i < 10; i++ {
a := rand.Int()
fmt.Printf("%d / ", a)
}
For i := 0; i < 5; i++ {
r := rand.Intn(8)
fmt.Printf("%d / ", r)
}
fmt.Println()
// Set the seed here, using the current nanosecond
Timens := int64(time.Now().Nanosecond())
rand.Seed(timens)
For i := 0; i < 10; i++ {
fmt.Printf("%2.2f / ", 100*rand.Float32())
}
}

Output

1
2
3
816681689 / 1325201247 / 623951027 / 478285186 / 1654146165 /
1951252986 / 2029250107 / 762911244 / 1372544545 / 591415086 / / 3 / 0 / 6 / 4 / 2 /22.10
/ 65.77 / 65.89 / 16.85 / 75.56 / 46.90 / 55.24 / 55.95 / 25.58 / 70.61 /