Go language introduction classic

Time:2020-11-21

Go Google new language reduces code complexity without losing application performance. It has the advantages of simple deployment, good concurrency, good language design and good execution performance

The major improvement of C-like language can access the underlying operating system, and provide powerful network programming and concurrent programming support.
Commonly used in

  • Network programming
  • System programming
  • Concurrent programming
  • Distributed programming

Go language is a modern programming language, which can be used to create excellent web server and system programs.

Go is a compiler language

go version
go version go1.15.1 darwin/amd64

Go environment configuration

[email protected] ~ % mkdir $HOME/go
[email protected] ~ % mkdir $HOME/go/bin
[email protected] ~ % mkdir $HOME/go/pkg
[email protected] ~ % mkdir $HOME/go/src
export GOPATH=$HOME/go

Share code with GitHub
mkdir -p $GOPATH/src/github.com/199305a
go hello world

package main
import (
    "fmt"
)
func main() {
    fmt.Printf("hello wprld")
}

Run HelloWorld
go run main.go

Types of go

Go is a statically typed language.

Data type is an important programming and computing structure

Boolean type

var b bool

numerical value
var i int = 3
Floating point number
var f float32 = 0.111
character string
var s string = "foo"
array
var beatles [4]string
Type check

reflect.TypeOf(s)

Type conversion

strconv.FormatBool(b)

variable
var s string = "foo"
Quick declaration variable

    var s,t string = "foo","bar"
    var (
        x string = "x"
        y int = 4
    )

Variables are declared unassigned, using the default zero value
Short declaration variable
s := "hello world"
You cannot use short variable declarations outside of a function
Ellipsis type declaration is usually used outside of functions
Using short variable declarations within functions

Understanding variable scope
Use pointer & S

     s,t  := "foo","bar"
     fmt.Println(&s,t)

Pointer passing print pointer content * x

func showMemoryAddress(x *string)  {
    fmt.Println(x);
    fmt.Println(*x);
}

Declare constant const

const  greeting string  = "hello world"

Using functions

The function takes input and returns output

func addUp(x int,y int) int {
    return  x + y
}

Returns multiple values

func getPrize() (int, string) {
    i := 2
    s := "goldfish"
    return i, s
}

Three points can be used to define an indefinite parameter function
Use named return value

func sayHi()(x,y string)  {
    x = "hello"
    y = "world"
    return 
}

Using recursive functions

Passing functions as values

func  anotherFunction(f func() string) string  {
    return  f()
}

func main() {
    fn := func() string {
        return "function called"
    }
    fmt.Println(anotherFunction(fn))
}

If else else else
Using the if statement

func  test()  {
    b := false
    if b {
        fmt.Println("b is true")
    }
}

Use the else statement else if
Using comparison operators
== != >= <= > <
Using arithmetic operators
+ - * / %
Using logical operators
&& || !
Using the switch statement

func test1() {
    i := 2
    switch i {
    case 1:
        fmt.Println("One")
    case 2:
        fmt.Println("Two")
    case 3:
        fmt.Println("Three")
     default:   
    }
}

Use the for loop range

func test2() {
    i := 0
    for i < 10 {
        fmt.Println("i is", i)
        i++

    }
    for i := 0; i < 10; i++ {
        fmt.Println("i is", i)
    }
    numbers := []int{1, 2, 3, 4}
    for i, n := range numbers {
        fmt.Println("The index of the loop is", i)
        fmt.Println("The value from the array is", n)
    }
}

Use the defer statement to execute multiple statements in reverse order

func test3()  {
    defer  fmt.Println("i am run after the func complete")
    fmt.Println("hello world")
}
hello world
i am run after the func complete

Array slicing and mapping
Fixed with array length
var cheese [2]string
Slicing is more flexible

var cheese = make([]string,2)

Add the element append in the slice
Delete element from slice, delete element at index 2

append(cheese[:2],cheese[2+1:]...)

Copy elements in slice

copy(cheese,cheeses[1:])

Use mapping

func test5()  {
    var players = make(map[string]int)
    players["cook"] = 32
    players["bairstow"] = 27
    players["stokes"] = 26
    fmt.Println(players["cook"])
}

Remove element from map

delete(players,"stokes")

What is a structure

A struct is a series of data fields with a specified data type

type Movie struct {
    Name string
    Rating float32
}

func test6()  {
     m := Movie{
         Name:   "Citizen Kane",
         Rating: 10,
     }
     fmt.Println(m)
}

Nested structure

Default values for custom structure data fields
Compare structures. If the structure types are different, there will be compilation errors

Understanding public and private values
Private values can only be used in their context
To export a structure and its fields, the field name must begin with an uppercase letter

Distinguish between pointer reference and value reference
Structs are value references
Becomes a pointer reference

n := &m

Creating methods and interfaces
Use method to attach to instance

func (m * Movie) summary() string  {
    
}
m.summary()

Create method set

Using methods and pointers


package main

import "fmt"

type Triangle struct {
    base float64
    height float64
}

func (t * Triangle) changeBase(f float64)  {
    t.base = f
    return
}

func main() {
  t := Triangle{base:3,height:1}
  t.changeBase(4)
  fmt.Println(t.base)
}

Use interface

type Robot interface {
    PowerOn() error
}

type  R2D2 struct {
    Broken bool
}

func (r * R2D2) PowerOn() error {
    if r.Broken {
        return  errors.New("R2D2 is broken")
    }else  {
        return nil
    }
}

Using strings
string literal

    s := "I am an interpreted string Literal"

Rune literal
`
s := “I am an interpretedn string Literal”
`
Concatenate strings using operators+

    s1 :="Oh sweet ignition" + "be my fuse"
    intToString := strconv.Itoa(i1)

String concatenation using buffer

    var buffer bytes.Buffer
    for i :=0;    i < 500;i++  {
        buffer.WriteString("z")
    }
    fmt.Println(buffer)

String byte slice
Processing strings
Converts a string to lowercase

    fmt.Println(strings.ToLower("VERY BEAUTIFUL"))

Find substring in string

    fmt.Println(strings.Index("VERY surface","face"))

Remove the first space in the string

    fmt.Println(strings.TrimSpace("VERY BEAUTIFUL"))

Processing error
Error handling and the uniqueness of go language

    file,err := ioutil.ReadFile("foo.txt")
    if err != nil{
         fmt.Println(err)
        return
    }
    fmt.Println("%s",file)

Understanding error types
Create error

    err := errors.New("Something went wrong")
    if err != nil {
         fmt.Println(err)
    }

Error returned from function

func Half(numberToHalf int) (int, error) {
    if numberToHalf%2 != 0 {
        return -1, fmt.Errorf("Cannot half %v", numberToHalf)
    }
    return numberToHalf / 2, nil
}

Error and availability
Careful use of panic will terminate the program

Using goroutine concurrency
Understanding concurrency
Concurrent and concurrent concurrent multiple tasks are executed simultaneously
Parallel tasks are executed in multiple parts

Concurrency is doing a lot of things at the same time. Parallelism is doing a lot of things at the same time

Understanding concurrency through web browser
Blocking and non blocking code

time.Sleep(time.Second * 2)

Using goroutine to handle concurrent operations
Add go before the function to make the function execute asynchronously

go    test6()

Introduction to the channel
Using channels

func slowFunc(c chan string)  {

    time.Sleep(time.Second * 2)
    c <- "slowFunc() finished"

}
func test1()  {
    c :=make(chan  string)
    go slowFunc(c)
    msg := <-c
    fmt.Println(msg)
}

Use the buffer channel to specify the number of channels, and the last close channel

func slowFunc(c chan string)  {

    time.Sleep(time.Second * 2)
    c <- "slowFunc() finished1"
    c <- "slowFunc() finished2"

}
func test1()  {
    c :=make(chan  string,2)
    go slowFunc(c)
    msg1 := <-c
    msg2 := <-c
    close(c)
    fmt.Println(msg1,msg2)
}

Blocking and process control
Blocking processes with for

func slowFunc(c chan string)  {
  t := time.NewTicker(1 * time.Second)
    for  {
        c <- "ping"
        <-t.C
    }
}
func test2()  {
    message := make(chan string)
    go slowFunc(message)
    for {
        msg := <-message
        fmt.Println(msg)
    }
}

Use channel as function parameter
< – on the left side of Chan means that the system is on the right side, which means write only

Using the select statement, when a piece of data is received, it is no longer blocked

func test3() {
    channel1 := make(chan string)
    channel2 := make(chan string)
    select {
    case msg1 := <-channel1:
        fmt.Println("received", msg1)
    case msg2 := <-channel2:
        fmt.Println("received", msg2)
    }
}

Exit channel
case <- stop

func sender(c chan string)  {
    t := time.NewTicker(1 * time.Second)
    for {
        c <- "I a messgae"
        <-t.C
    }
}

func test1()  {
    messages := make(chan string)
    stop := make(chan  bool)
    go sender(messages)
    go func() {
        time.Sleep(time.Second * 2)
        fmt.Println("Time is up")
        stop <- true
    }()
    for  {
        select {
        case <-stop:
            return
        case msg := <-messages:
            fmt.Println(msg)

        }
    }
}

Code reuse using packages
Import package

import (
    "fmt"
    "time"
)

Using third party packages
go get github.com/golang/example/stringutil

func test2()  {
    s := "ti ercesxsc"
    fmt.Println(stringutil.Reverse(s))
}

Managing third party dependencies
go get u all

GO111MODULE=auto
go run hello.go

create package

package temperature

func CtoF(c float64)float64 {
    return (c * (9 / 5)) + 32
}
func FtoC(c float64)float64 {
    return (c - 32) * (9 / 5)
}

Naming convention of go language
Go code format setting
Using gofmt
gofmt temperature.go
gofmt -w temperature.go

Configure text editor