Go learning is over

Posted by wgh on Wed, 06 Oct 2021 15:36:37 +0200

Go learning is over

  • Google open source
  • Compiled language
  • Language in the 21st century (2007)

0.HelloWord

Create a file named hello.go, where. Go is the suffix of the go type file.

package main 

import "fmt"

func main(){
	fmt.Printf("Hello World!");
}

Then open cmd and enter the directory of the file: enter go bulid hello.go

Under windows, a file named hello.exe will be generated in this directory.

We can enter hello under cmd to see the print information.

characteristic

Simple syntax, high development efficiency and good execution performance.

use

Using the fmt formatting tool of Go, the settings under GoLand:

Settings - > file watchers - > add go fmt.

study

1. Declaration and assignment, variables and constants

Variables declared in Go language must use var.

var name string //Separate declaration
var age int
var isOk bool

//Batch declaration
var(
	name string
    age int
    isOk bool
)
const mo string = "1234"
cosnt m = "12345"
const(
	c1 = 1
    c2 = 1.5
    c3 = "abc"
)
var name string = "herio" //Declare simultaneous assignment
var name = "herio" //Automatic derivation type
name := "herio" //Short variable declaration, which can only be used in functions

Go has well-known types, such as int, which determines the appropriate length according to your hardware. It means that on 32-bit hardware, it is 32-bit; It is 64 bit on 64 bit hardware. Note: int is one of 32 or 64 bits and will not be defined as other values. uint is the same.

If you want to specify its length, you can use int32 or uint32. The complete list of integer types (signed and unsigned) is int8, int16, int32, int64 and byte, uint8, uint16, uint32, uint64. Byte is an alias for uint8. Float type values are float32 and float64 (no float type). 64 bit integers and floating-point numbers are always 64 bits, even on a 32-bit architecture.

2. Output

Println line feed printing, Printf formatted output, Print non line feed printing.

3. Constant counter iota

package main

import "fmt"

const (
	a1 = iota //Constant counter
	a2
	a3
	a4
)

func main() {
	fmt.Print(a1)
	fmt.Print(a2)
	fmt.Print(a3)
	fmt.Print(a4)
}

//0123

//Discrimination
const(
	a1 = iota //0
	a2 = _  //1
	a3 = iota //2
	a4	//3
)

const(
	a1,a2= iota ,iota+1  // 0 ,1
    a3,a4= iota+2, iota+3 // 3,4
)

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

4. Data type

The output variable can be% v and the print type can be% T.

Multiple lines of strings can be printed with backquotes. The backquoted string is the original output and will not be escaped.

Strings are immutable in Go.


complex

	s := 5 + 4i
	fmt.Printf("%T %v\n", s, s)
	fmt.Print(s)
/*
complex128 (5+4i)
(5+4i)
*/

operator

Although Go does not support operator overloading (or method overloading), some built-in operators support overloading. For example+
Can be used for integers, floating point numbers, complex numbers, and strings (string addition means concatenating them).

keyword

5.if and for loops, switch, goto

Similar to C, C removes parentheses, and for range is similar to for each.

continue and break are similar to C.

Flag:
	for i := 0; i < 10; i++ {
		for j := 0; j < 10; j++ {
			if j > 5 {
				break Flag
			}
			fmt.Printf("j=%d\n", j)
		}
	}
	fmt.Println("over")
/*
j=0
j=1
j=2
j=3
j=4
j=5
over
*/
package main

import "fmt"

func main() {
	a := 10
	if a > 10 {
		fmt.Println("a>10")
	} else {
		fmt.Println("a<=10")
	}

	for i := 0; i < 10; i++ {
		fmt.Println(i)
	}

	s := "Herio my boy"
	for i, c := range s {
		fmt.Printf("%d : %c\n", i, c)
	}
}
/*
a<=10
0
1
2
3
4
5
6
7
8
9
0 : H
1 : e
2 : r
3 : i
4 : o
5 :  
6 : m
7 : y
8 :  
9 : b
10 : o
11 : y
*/

switch and goto are similar to C

package main
import "fmt"
func main() {
    var num1 int = 100
    switch num1 {
    case 98, 99:
        fmt.Println("It's equal to 98")
    case 100: 
        fmt.Println("It's equal to 100")
    default:
        fmt.Println("It's not equal to 98 or 100")
    }
}

6. Arrays and slices


package main

import "fmt"

func main() {
	a := [...]int{1, 1, 4, 5, 1, 4}
	fmt.Println(a)
	fmt.Printf("%T\n", a)

	var b [3][2]int
	b = [3][2]int{
		{1, 2},
		{3, 4},
		{5, 6},
	}
	fmt.Println(b)
}
/*
[1 1 4 5 1 4]
[6]int
[[1 2] [3 4] [5 6]]
*/

Create a slice with make()

When the correlation array has not been defined, we can use the make() function to create a slice and create the correlation array: var slice1 []type = make([]type, len).

It can also be abbreviated as slice1: = make ([] type, len), where len is the length of the array and also the initial length of slice.

So define S2: = make ([] int, 10), then cap(s2) == len(s2) == 10.

make accepts two parameters: the type of element and the number of elements in the slice.

If you want to create a slice1, which does not occupy the whole array, but only takes several items with len, then just: slice1: = make ([] type, len, cap).

The use of make is func make([]T, len, cap), where cap is an optional parameter.

Therefore, the following two methods can generate the same slice:

  1. make([]int, 50, 100)
  2. new([100]int)[0:50]


Declare a map

	mp := make(map[string]int)
	mp["herio"] = 123
	fmt.Printf("%d\n", mp["herio"])
	val, ok := mp["herio"]
	fmt.Print(val, ok)
/*
123
123 true
*/

7. Pointer

package main

import "fmt"

func main() {
   var a int= 20   /* Declare actual variables */
   var ip *int        /* Declare pointer variables */

   ip = &a  /* Storage address of pointer variable */

   fmt.Printf("a The address of the variable is: %x\n", &a  )

   /* Storage address of pointer variable */
   fmt.Printf("ip Pointer address of variable storage: %x\n", ip )

   /* Accessing values using pointers */
   fmt.Printf("*ip Value of variable: %d\n", *ip )
}
a The address of the variable is: 20818a220
ip Pointer address of variable storage: 20818a220
*ip Value of variable: 20

Go null pointer

When a pointer is defined and not assigned to any variable, its value is nil.

nil pointers are also called null pointers.

Like null, None, nil and null in other languages, nil conceptually refers to zero value or null value.

A pointer variable is usually abbreviated as ptr.

View the following examples:

package main

import "fmt"

func main() {
   var  ptr *int

   fmt.Printf("ptr The value of is : %x\n", ptr  )
}
ptr The value of is : 0

function

Delay code


Function as value

Panic panic and recovery

3, Package

cmd to view go's environment configuration env:

go env

C:\Program Files\Go\src

All the bags are stored here.

Custom package: even.go

package even

func Even(i int) bool {
	return i % 2 == 0
}

func odd(i int)bool {
	return i % 2 == 1
}

Here, functions starting with uppercase can be exported.

Create a folder named even in the C:\Program Files\Go\src directory, and then put the file in that directory.

Then you can import the package for use.

package main

import (
	"even"
	"fmt"
)

func main() {
	a := 10
	fmt.Printf("%d : %v", a, even.Even(a))
}
/*
10 : true
*/

Package documentation

Some common packages

  • fmt implements formatted I/O functions
  • io contains the original I/O operation interface
  • bufio implements buffered I/O
  • Sort sort
  • Conversion between strconv string and basic data
  • os provides a platform independent operating system function interface
  • sync basic synchronization primitive
  • flag command line parsing

4, Memory allocation


Remember that make only applies to map, slice and channel, and does not return a pointer. You should get a specific pointer with new.

5, Custom type

Note that capitalized fields can be exported, that is, they can be read and written in other packages. The field name starts with a lowercase letter and is private to the current package. The function definition of the package is similar, see Chapter 3 for more details.

6, Interface, concurrency, communication

Waiting to learn

Reference content

e-book https://www.bookstack.cn/read/the-way-to-go_ZH_CN/eBook-07.2.md

video https://www.bilibili.com/video/BV16E411H7og?p=28

Go Chinese website: https://studygolang.com/pkgdoc

Li Wenzhou's blog: https://www.liwenzhou.com/

Topics: Go