[GO Development Series - Foundation] Introduction to Go Foundation

Posted by garygay on Thu, 22 Aug 2019 13:13:45 +0200

[GO Development Series - Foundation] Introduction to Go Foundation

The Characteristics of Golang Language

The Go language not only has the security and performance of static compiler language, but also has the high efficiency of dynamic language development and maintenance.

Static compiler language: Static compiler language is a language that can determine the data type of variables at compile time. Most static type languages require that the data type be declared before using variables.

Dynamic language: Dynamic language is a language that determines the data type at runtime. Variables do not need type declaration before they are used. Usually the type of variable is the type of the value assigned.

  • 1. Include the grammar and control structure similar to C language, basic data type, call parameter transfer value, pointer, etc.
  • 2. Introducing the concept of package, every file in Go language belongs to one package and cannot exist independently.
  • 3. Garbage collection mechanism, automatic memory recovery;
  • 4. Natural concurrence;
  • (1) Supporting concurrency at the linguistic level;
  • (2) goroutine, lightweight thread, efficient use of multi-core;
  • (3) Implementation of concurrent model based on CPS (Communicating Sequential Processes);
  • 5. Pipeline communication mechanism, through which different goroute s can communicate.
  • 6. Functions can return multiple values.

[2] Examples of Basic Grammar in Golang Language

[2.1] Variables

The Use of Identifiers in Goang

package main

import "fmt"

//The Use of Identifiers in Goang
func main() {

	//Strictly case-sensitive in Golang
	//num and num are different variables in golang
	var num int = 10
	var Num int = 20
	//Output: num=10 Num=20
	fmt.Printf("num=%v Num=%v\n", num, Num)

	//Identifiers cannot contain spaces
	//var ab c int = 30

	//_ Is an empty identifier for occupancy
	// var _ int = 40 //error
	// fmt.Println(_)

	var int int = 90
	//Output: 90
	fmt.Println(int)
}

The Use of Variables in Goang

package main

import "fmt"

//The Use of Variables in Goang
func main() {
	//Variable usage of golang 1
	//The first is to specify the variable type and use the default value if it is not assigned after declaration.
	// The default value of int is 0. The default value of other data types will be introduced shortly.
	var i int
	//Output: i= 0
	fmt.Println("i=", i)

	//The second is to determine the type of variable according to its value (type deduction)
	var num = 10.11
	//Output: num= 10.11
	fmt.Println("num=", num)

	//Third: omit var, note: = The variable on the left shouldn't have been declared, otherwise it will lead to compilation errors.
	//The following is equivalent to var name string name = Tom
	// := Yes: You can't omit it or you'll make a mistake.
	name := "tom"
	//Output: name= tom
	fmt.Println("name=", name)

}
package main

import "fmt"

//Define global variables
var n1 = 100
var n2 = 200
var name = "jack"

//The above declaration can also be changed to a one-time declaration.
var (
	n3    = 300
	n4    = 900
	name2 = "mary"
)

func main() {

	//This case demonstrates how golang declares multiple variables at once
	var n5, n6, n7 int
	//Output: n5= 0 n6= 0 n7= 0
	fmt.Println("n5=", n5, "n6=", n6, "n7=", n7)

	//Ways to declare multiple variables at one time 2
	var n8, name3, n9 = 100, "tom", 888
	//Output: n8= 100 name3= tom n9= 888
	fmt.Println("n8=", n8, "name3=", name3, "n9=", n9)

	//The way to declare multiple variables at one time 3. Type inference can also be used
	n10, name4, n11 := 100, "tom~", 888
	//Output: n10= 100 name4= tom~ n11= 888
	fmt.Println("n10=", n10, "name4=", name4, "n11=", n11)

	//Output global variables
	//Output: n1= 100 name= jack n2= 200
	fmt.Println("n1=", n1, "name=", name, "n2=", n2)
	//Output: n3= 300 name2= mary n4= 900
	fmt.Println("n3=", n3, "name2=", name2, "n4=", n4)

}
package main

import (
	"fmt"
	//In order to use variables or functions in utils.go files, we need to introduce the model package first.
	"GO_LEARN_CODE/chapter03/demo04/model"
)

//Notes for variable usage
func main() {

	//The data values of this region can change continuously in the same type range.
	var i int = 10
	i = 30
	i = 50
	//Output: i= 50
	fmt.Println("i=", i)
	//I = 1.2//int, because the data type cannot be changed

	//Variables cannot be renamed in the same scope (in a function or block of code)
	//var i int = 59
	//i := 99
	//We use the heroName package name. flag of utils.go
	//Output: Songjiang
	fmt.Println(model.HeroName)

}

package model

//Define a variable
var HeroName string = "Song Jiang"

Integer type usage in golang

package main

// import "fmt"
// import "unsafe"
import (
	"fmt"
	"unsafe"
)

// Integer type usage in golang
func main() {

	var i int = 1
	//Output: i= 1
	fmt.Println("i=", i)

	//Test the range of int8 - 128 - 127.
	//Other int16, int32, int64, analogy...
	var j int8 = 127
	//Output: j= 127
	fmt.Println("j=", j)

	//Test the range of uint 8 (0-255), other uint 16, uint 32, uint 64 and so on.
	var k uint16 = 255
	// Output: k= 255
	fmt.Println("k=", k)

	//Use of int, uint, rune, byte
	var a int = 8900
	//Output: a= 8900
	fmt.Println("a=", a)
	var b uint = 1
	var c byte = 255
	//Output: b= 1 c= 255
	fmt.Println("b=", b, "c=", c)

	//Use details of integers
	var n1 = 100 // What type is n1?
	//Here we show you how to view the data type of a variable.
	//fmt.Printf() can be used for formatting output.
	//Output: Type int of n1
	fmt.Printf("n1 Types of %T \n", n1)

	//How to view byte size and data type of a variable in a program (more used)
	var n2 int64 = 10
	//unsafe.Sizeof(n1) is a function of the unsafe package that returns the number of bytes occupied by the N1 variable.
	//Output: n2 type Int64 n2 takes up 8 bytes
	fmt.Printf("n2 Types of %T  n2 The number of bytes occupied is %d ", n2, unsafe.Sizeof(n2))

}

Use of Goang Median Types

package main

import (
	"fmt"
	"unsafe"
)

//Use of Goang Median Types
func main() {

	var price float32 = 89.12
	//Output: price= 89.12
	fmt.Println("price=", price)
	var num1 float32 = -0.00089
	var num2 float64 = -7809656.09
	//Output: num1=-0.00089 num2=-7.80965609e+06
	fmt.Println("num1=", num1, "num2=", num2)

	//The tail number may be lost, resulting in loss of accuracy. - 123.0000901
	var num3 float32 = -123.0000901
	var num4 float64 = -123.0000901
	num3= -123.00009 num4= -123.0000901
	fmt.Println("num3=", num3, "num4=", num4)

	//Golang's floating-point default declaration is float64
	var num5 = 1.1
	//Output: The data type of num5 is float64
	fmt.Printf("num5 The data type is %T \n", num5)

	//Decimal form: e.g. 5.12.512 (must have decimal point)
	num6 := 5.12
	num7 := .123 //=> 0.123
	//Output: num6= 5.12 num7= 0.123
	fmt.Println("num6=", num6, "num7=", num7)

	//The Form of Scientific Counting
	num8 := 5.1234e2   // 2 power of 5.1234*10
	num9 := 5.1234E2   // 2 power of 5.1234*10
	num10 := 5.1234E-2 // 2 th power 0.051234 of 5.1234/10
	//Output: num8= 512.34 num9= 512.34 num10= 0.051234
	fmt.Println("num8=", num8, "num9=", num9, "num10=", num10)
	/**
	 * byte Equivalent to int8, commonly used to process ascii characters
	 * rune Equivalent to int32, commonly used to handle unicode or utf-8 characters
	 */
	var c1 rune = 'north'
	//Output: C1 = 212714
	fmt.Println("c1=", c1, unsafe.Sizeof(c1))

}

Conversion of Basic Data Types in Goang

package main

import (
	"fmt"
)

// Conversion of Basic Data Types in Goang
func main() {

	var i int32 = 100
	//I = float
	var n1 float32 = float32(i)
	var n2 int8 = int8(i)
	var n3 int64 = int64(i) //Low Precision - > High Precision
	//Output: i=100 n1=100 n2=100 n3=100
	fmt.Printf("i=%v n1=%v n2=%v n3=%v \n", i, n1, n2, n3)

	//What is converted is the data stored in the variable (i.e. the value), and the data type of the variable itself remains unchanged.
	//Output: i type is int32
	fmt.Printf("i type is %T\n", i) // int32

	//In conversion, for example, converting int64 to int8 [128 - 127], there will be no error at compile time.
	//It's just that the result of the transformation is treated as overflow, which is different from what we want.
	var num1 int64 = 999999
	var num2 int8 = int8(num1)
	//Output: num2= 63
	fmt.Println("num2=", num2)

}

Pointer type usage in golang

package main

import (
	"fmt"
)

//Pointer type in golang
func main() {

	//Basic data types in memory layout
	var i int = 10
	// What's the address of i, & I
	//Output: i address = 0xc00004e080
	fmt.Println("i Address=", &i)

	//The following var PTR * int = & & I
	//1. ptr is a pointer variable
	//2. Type of ptr*int
	//3. The value of PTR itself & I
	var ptr *int = &i
	//Output: ptr=0xc00004e080
	fmt.Printf("ptr=%v\n", ptr)
	//Output: The address of PTR = 0xc000076020ptr points to value = 10
	fmt.Printf("ptr Address=%v", &ptr)
	fmt.Printf("ptr Pointing value=%v", *ptr)

}

Character type usage in golang

package main

import (
	"fmt"
)

//Character type usage in golang
func main() {

	var c1 byte = 'a'
	var c2 byte = '0' //Character 0

	//When we output the byte value directly, it is the code value of the corresponding character output.
	// 'a' ==>
	//Output: c1= 97 c2= 48
	fmt.Println("c1=", c1)
	fmt.Println("c2=", c2)
	//If we want to output the corresponding characters, we need to use formatted output
	//Output: c1=a c2=0
	fmt.Printf("c1=%c c2=%c\n", c1, c2)

	//var c3 byte ='north'//overflow overflow
	var c3 int = 'north' //Overflow overflow
	//Output: c3 = North c3 corresponding code value = 21271
	fmt.Printf("c3=%c c3 Corresponding Code Value=%d\n", c3, c3)

	//You can assign a number to a variable directly, and when you format the output% c, the unicode character corresponding to that number will be output.
	var c4 int = 22269 // 22269 - >'Guo'120 - >'x'
	//Output: c4 = country
	fmt.Printf("c4=%c\n", c4)

	//Character types are computable, equivalent to an integer, and are transported according to code values.
	var n1 = 10 + 'a' //  10 + 97 = 107
	//Output: n1= 107
	fmt.Println("n1=", n1)

}

 

bool type usage in golang

package main

import (
	"fmt"
	"unsafe"
)

//bool type usage in golang
func main() {
	var b = false
	//Output: b= false
	fmt.Println("b=", b)
	//Output: space occupied by b = 1
	//Matters needing attention
	//1. bool type takes up one byte of storage space
	fmt.Println("b Occupancy space =", unsafe.Sizeof(b))
	//2. bool type can only be true or false
}

Use of string type in golang

package main

import (
	"fmt"
)

//Use of string type in golang
func main() {
	//Basic use of string
	var address string = "Beijing Great Wall 110 hello world!"
	//Output: Beijing Great Wall 110 hello world!
	fmt.Println(address)

	//Once the string is assigned, the string cannot be modified: in Go, the string is immutable
	//var str = "hello"
	//STR [0]='a'// There is no way to modify the str content, that is, the strings in go are immutable.

	//Two Representations of Strings
	//(1) Double quotation marks, which recognize escape characters;
	//(2) Inverse quotation marks, which are output in the native form of strings, including newlines and special characters, can prevent attacks and output source code.
	str2 := "abc\nabc"
	/**
	 * Output:
	 * abc
	 * abc
	 */
	fmt.Println(str2)

	//Backquotation marks used``
	str3 := ` 
	package main
	import (
		"fmt"
		"unsafe"
	)
	
	//Demonstrate bool type usage in golang
	func main() {
		var b = false
		fmt.Println("b=", b)
		//Matters needing attention
		//1. bool type takes up one byte of storage space
		fmt.Println("b Occupancy space =", unsafe.Sizeof(b) )
		//2. bool type can only be true or false
		
	}
	`
	fmt.Println(str3)

	//String splicing
	var str = "hello " + "world"
	str += " haha!"

	fmt.Println(str)
	//When a splicing operation is very long, what should we do? We can write in separate lines, but note that we need to keep + in the previous line.
	str4 := "hello " + "world" + "hello " + "world" + "hello " +
		"world" + "hello " + "world" + "hello " + "world" +
		"hello " + "world"
	fmt.Println(str4)

	var a int          // 0
	var b float32      // 0
	var c float64      // 0
	var isMarried bool // false
	var name string    // ""
	//Here% v represents output by the value of the variable
	//Output: a=0,b=0,c=0,isMarried=false name=
	fmt.Printf("a=%d,b=%v,c=%v,isMarried=%v name=%v", a, b, c, isMarried, name)
}

Converting basic data into string in golang

package main

import (
	"fmt"
	"strconv"
	_ "unsafe"
)

//Converting basic data into string in golang
func main() {

	var num1 int = 99
	var num2 float64 = 23.456
	var b bool = true
	var myChar byte = 'h'
	var str string //Empty str

	//Convert the fmt.Sprintf method in the first way
	//Output: str type string str="99"
	str = fmt.Sprintf("%d", num1)
	fmt.Printf("str type %T str=%q\n", str, str)
	//Output: str type string str="23.456000"
	str = fmt.Sprintf("%f", num2)
	fmt.Printf("str type %T str=%q\n", str, str)
	//Output: str type string str="true"
	str = fmt.Sprintf("%t", b)
	fmt.Printf("str type %T str=%q\n", str, str)
	//Output: str type string str="h"
	str = fmt.Sprintf("%c", myChar)
	fmt.Printf("str type %T str=%q\n", str, str)

	//The second way strconv function
	var num3 int = 99
	var num4 float64 = 23.456
	var b2 bool = true
	//Output: str type string str="99"
	str = strconv.FormatInt(int64(num3), 10)
	fmt.Printf("str type %T str=%q\n", str, str)

	// strconv.FormatFloat(num4, 'f', 10, 64)
	// Explanation:'f'Format 10: Represents that decimal digits are reserved at 10 bits 64: Represents that this decimal is float64
	// Output: str type string str="23.4560000000"
	str = strconv.FormatFloat(num4, 'f', 10, 64)
	fmt.Printf("str type %T str=%q\n", str, str)
	//Output: str type string str="true"
	str = strconv.FormatBool(b2)
	fmt.Printf("str type %T str=%q\n", str, str)

	//There is a function Itoa in the strconv package
	//Output: str type string str="4567"
	var num5 int64 = 4567
	str = strconv.Itoa(int(num5))
	fmt.Printf("str type %T str=%q\n", str, str)

}

string in golang converts to basic data types

package main

import (
	"fmt"
	"strconv"
)

// string in golang converts to basic data types
func main() {

	// Output: B type bool B = true
	var str string = "true"
	var b bool
	// b, _ = strconv.ParseBool(str)
	// Explain
	// 1. The strconv. ParseBool (str) function returns two values (value bool, err error)
	// 2. Because I just want to get value bool, I don't want to get err, so I use _ignore
	b, _ = strconv.ParseBool(str)
	//Output: B type bool B = true
	fmt.Printf("b type %T  b=%v\n", b, b)
	// Output: N1 type Int64 N1 = 1234590
	//			n2 type int n2=1234590
	var str2 string = "1234590"
	var n1 int64
	var n2 int
	n1, _ = strconv.ParseInt(str2, 10, 64)
	n2 = int(n1)
	//Output: N1 type Int64 N1 = 1234590
	fmt.Printf("n1 type %T  n1=%v\n", n1, n1)
	//Output: n2 type int n2=1234590
	fmt.Printf("n2 type %T n2=%v\n", n2, n2)
	// Output: f1 type float64 f1=123.456
	var str3 string = "123.456"
	var f1 float64
	f1, _ = strconv.ParseFloat(str3, 64)
	//Output: f1 type float64 f1=123.456
	fmt.Printf("f1 type %T f1=%v\n", f1, f1)

	// Output: n3 type int64 n3=0
	var str4 string = "hello"
	var n3 int64 = 11
	n3, _ = strconv.ParseInt(str4, 10, 64)
	//Output: n3 type int64 n3=0
	fmt.Printf("n3 type %T n3=%v\n", n3, n3)

}

[2.2] Operator

Summary of Operator Notices in Goang Language

++,--Operator

package main

import (
	"fmt"
	_ "fmt"
)

func main() {

	//In golang, ++ and -- can only be used independently.
	var i int = 8
	// var a int
	// a = i+// error, i++ can only be used independently
	// a = i - / / error, i - - can only be used independently

	// Compilation error
	// if i++ > 0 {
	// 	fmt.Println("ok")
	// }

	i++
	// + + i // Error, no previous + + in golang
	fmt.Println("i=", i)
	i--
	// i// Error, before Goang--
	fmt.Println("i=", i)
}

[2.3] Typical process control examples

break summary of golang language

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {

	//In order to generate a random number, we need a rand to set up a seed.
	//time.Now().Unix(): Returns a number of seconds from 0:0:0:0 to the present from 1970:01:01
	//rand.Seed(time.Now().Unix())
	//How to generate 1-100 integers randomly
	//n := rand.Intn(100) + 1 // [0 100)
	//fmt.Println(n)

	//Randomly generate a number of 1-100 until the number 99 is generated. See how many times you have shared it.
	//Analytical thinking:
	//Write an infinite loop of control, and then continue to generate random numbers, when 99 is generated, then exit the infinite loop== break
	var count int = 0
	for {
		rand.Seed(time.Now().UnixNano())
		n := rand.Intn(100) + 1
		fmt.Println("n=", n)
		count++
		if n == 99 {
			break //Represents jumping out of the for loop
		}
	}

	fmt.Println("Generation 99 is used together ", count)

	//Here's a demonstration of using break in the form of a specified tag
	//When a break statement appears in a multi-level nested statement block, the tag can indicate which level of statement block to terminate.
	//lable2:
	for i := 0; i < 4; i++ {
	lable1: // Set a label
		for j := 0; j < 10; j++ {
			if j == 2 {
				// Brea // break defaults to jump out of the latest for loop
				break lable1
				// break lable2
			}
			//break : j=0,j=1; i=0,i=1,i=2,i=3;
			//break lable1 : j=0,j=1; i=0,i=1,i=2,i=3;
			//Break lable2: J = 0, J = 1; I will not print;
			fmt.Println("j=", j)
		}
		fmt.Println("i=", i)
	}
}

Summary of Goang Language continue

package main

import "fmt"

func main() {

	//continue case
	//Here's a demonstration of the format of the specified label to use
lable2:
	for i := 0; i < 4; i++ {
		// lable1: // Set a label
		for j := 0; j < 10; j++ {
			if j == 2 {
				// continue
				// continue lable1
				continue lable2
			}
			// continue : i=0--3;j=0,1,3--9;
			// continue lable1 : i=0--3;j=0,1,3--9;
			// Continue lable 2: J = 0,1; I does not print
			fmt.Println("j=", j)
		}
		fmt.Println("i=", i)
	}
}

Summary of Goang Language for

package main

import (
	"fmt"
)

func main() {

	//The first way to write for loops
	for i := 1; i <= 10; i++ {
		fmt.Println("Hello, Shang Silicon Valley", i)
	}

	//The second way to write for loops
	j := 1        //Initialization of cyclic variables
	for j <= 10 { //Cyclic conditions

		fmt.Println("Hello, Shang Silicon Valley~", j)
		j++ //Iteration of cyclic variables
	}

	//The third way to write for loops, which is usually used in conjunction with break
	k := 1
	for { // It's also equivalent here for;;;;;;___________;{
		if k <= 10 {
			fmt.Println("ok~~", k)
		} else {
			break //break is to jump out of the for loop
		}
		k++
	}

	//String traversal mode 1 - traditional mode
	var str string = "hello,world!Beijing"
	for i := 0; i < len(str); i++ {
		fmt.Printf("%c \n", str[i]) //Use the subscript...
	}

	//String traversal mode 1 - traditional mode
	str2 := []rune(str) // That's to turn str into [] rune
	for i := 0; i < len(str2); i++ {
		fmt.Printf("%c \n", str2[i]) //Use the subscript...
	}

	//String traversal 2-for-range
	str = "abc~ok Shanghai"
	for index, val := range str {
		fmt.Printf("index=%d, val=%c \n", index, val)
	}
}

goto / return summary of golang language

package main

import (
	"fmt"
)

func main() {

	var n int = 30
	//Demonstrate the use of goto
	fmt.Println("GOTO1")
	if n > 20 {
		goto label1
	}
	fmt.Println("GOTO2")
	fmt.Println("GOTO3")
	fmt.Println("GOTO4")
label1:
	fmt.Println("GOTO5")
	fmt.Println("GOTO6")
	fmt.Println("GOTO7")

	//Demonstrate the use of return
	fmt.Println("RETURN1")
	if n > 20 {
		return
	}
	fmt.Println("RETURN2")
	fmt.Println("RETURN3")
	fmt.Println("RETURN4")
	fmt.Println("RETURN5")
	fmt.Println("RETURN6")
	fmt.Println("RETURN7")
}

Summary of golang language switch

package main

import (
	"fmt"
)

func main() {

	//Automatic exit without break after switch matching in go language
	var n1 int32 = 51
	var n2 int32 = 20
	switch n1 {
	case n2, 10, 5: // There can be multiple expressions behind case
		fmt.Println("ok1")
	case 90:
		fmt.Println("ok2~")

	}

	//The switch can also be used without expressions, similar to if--else branches. [Case demonstration]
	var age int = 10

	switch {
	case age == 10:
		fmt.Println("age == 10")
	case age == 20:
		fmt.Println("age == 20")
	default:
		fmt.Println("Not matched")
	}

	//Scope can also be judged in case
	var score int = 90
	switch {
	case score > 90:
		fmt.Println("Excellent results..")
	case score >= 70 && score <= 90:
		fmt.Println("Excellent results...")
	case score >= 60 && score < 70:
		fmt.Println("Achievement pass...")
	default:
		fmt.Println("Fail,")
	}

	//After switch, you can also declare / define a variable directly, ending with a semicolon and not recommended.

	switch grade := 90; { // In golang, you can write like this
	case grade > 90:
		fmt.Println("Excellent results~..")
	case grade >= 70 && grade <= 90:
		fmt.Println("Excellent results~...")
	case grade >= 60 && grade < 70:
		fmt.Println("Achievement pass~...")
	default:
		fmt.Println("Fail,~")
	}

	//Breakthrough through fallthrought of switch
	//Adding fallthrought after the case block will continue to execute the next case
	var num int = 10
	switch num {
	case 10:
		fmt.Println("ok1")
		fallthrough //Default can only penetrate one layer
	case 20:
		fmt.Println("ok2")
		fallthrough
	case 30:
		fmt.Println("ok3")
	default:
		fmt.Println("Not matched..")
	}
}

Summary of golang language while

package main

import "fmt"

func main() {

	//Use while to output 10 sentences "hello,world"
	//Initialization of cyclic variables
	var i int = 1
	for {
		if i > 10 { //Cyclic conditions
			break // Jump out of the for loop and end the for loop
		}
		fmt.Println("hello,world", i)
		i++ //Iteration of cyclic variables
	}

	fmt.Println("i=", i)

	//Use do...while to complete the output of 10 sentences "hello,ok"“
	var j int = 1
	for {
		fmt.Println("hello,ok", j)
		j++ //Iteration of cyclic variables
		if j > 10 {
			break //break is to jump out of the for loop
		}
	}
}

 

Reference thanks

This blog is a summary of the bloggers'learning practice and refers to the blogs of many bloggers. Thank you. If bloggers have any shortcomings, please criticize and correct them.

Core Programming of Shangsi Valley Han Shunping Go Language

[2]The Difference between Static Language and Dynamic Language

 

Topics: Go Unix ascii Programming