I’ve been browsing articles on the Internet lately, and I keep coming across the go language. See much, I also can’t restrain the curiosity of the heart, to find out.

Go is a very special language with the following characteristics:

  • No “objects”, no inherited polymorphism, no generics, no try/catch
  • Interface, functional programming, CSP concurrency model (Goroutine + Channel)
  • Grammar is simple

I saw someone on the Internet said, go language learning is very simple ah, than JS is also simple. Ah? This analogy also inspired me to learn go, I want to see how easy!!

The development environment

No more nonsense, hurriedly put up the go development environment can be happy to masturbation code ah.

1. Install

Go can be downloaded from studygolang.com/dl

Gopath and goroot

2. Development tools

Development tools I use is Goland, out of the box, comfortable.

grammar

Define variables

Go uses the var keyword to declare variables. This is the same as js.

package main

import "fmt"

func variableInitialValue(a) {
    // The variable name is followed by the variable type
    var a int = 3
    var s string = "abc"
    fmt.Println(a, s)
}
variableInitialValue() // 3 abc
Copy the code

In addition, if you just define variables and you don’t assign values, go will have initial values like int will be 0, string will be an empty string. This point and JS is not the same.

In addition, go can automatically infer variable types.

func variableTypeDeduction(a) {
    var a, b, c = 3."a".true
	fmt.Println(a, b, c)
}
variableTypeDeduction() // 3 a true
Copy the code

At the same time, go provides an easy way to declare variables inside functions. Here we focus on these three keywords inside functions.

func variableShortCut(a) {
    a, b, c := 3."a".true
    fmt.Println(a, b, c)
}
variableShortCut() // 3 a true
Copy the code

We mentioned above that notice these three words in the function, why?

package main

import "fmt"

var a = 1 // No problem
b := 2 // You can't write this outside a function
Copy the code

We notice that there is a package main at the beginning of the file, that is, there are no global variables in GO, only variables within the package.

Alternatively, we can declare multiple variables at the same time by writing:

var (
    a = 1
    b = 2
    c = 3
)
Copy the code

Built-in variable types

  • bool, string
  • (u)int,(u)int8,(u)int16,(u)int32,(u)int64,uintptr
  • byte, rune
  • float32, float64, complex64, complex128

Rune is the char type in go. Byte is 8-bit and rune is 32-bit. Complex is a complex number.

Cast casting

Let’s look at the code below:

func triangle(a) {
    var a, b int = 3.4
    var c int
    c = int(math.Sqrt(float64(a*a + b*b)))
    fmt.Println(c)
}
Copy the code

Sqrt(a*a + b*b). This will help us avoid a lot of bugs on large projects.

Constants defined

Constants are defined using const in GO, just like in ES6. Use the same method as var, but do not abbreviate it.

const a = "2"
Copy the code

Enumerated type

func enums(a) {
    const (
    	cpp = iota
    	java
    	python
    	golang
    	js
    )

    // b, kb, mb, gb, tb, pb
    const (
    	b = 1< < (10 * iota)
    	kb
    	mb
    	gb
    	tb
    	pb
    )

    fmt.Println(cpp, java, python, js)
    fmt.Println(b, kb, mb, gb, tb, pb)
}
enums() 
// 0 1 2 4
// 1 1024 1048576 1073741824 1099511627776 1125899906842624
Copy the code

Iota stands for autoincrement and can also participate in operations.

if else

There are no parentheses in the if and for conditions

Now suppose we have an A.txt in the same directory as our.go file

package main

import (
	"fmt"
	"io/ioutil"
)

func main(a) {
    const filename = "a.txt"
    ifcontents, err := ioutil.ReadFile(filename); err ! =nil {
    	fmt.Println(err)
    } else {
    	fmt.Printf("%s\n", contents)
    }
    // The following code does not contain contents
    // fmt.Printf("%s\n", contents)
}
Copy the code

If contents, err := ioutil.readfile (filename); err ! = nil {}, which I don’t agree with in terms of readability, but I read on the Internet that after you finish ifelse, the contents variable is automatically recycled, because contents is inside the scope of the if statement.

switch

In go, the switch breaks automatically unless fallthrough is used

func grade(score int) string {
    g := ""
    switch {
    case score < 0 || score > 100:
    	panic(fmt.Sprintf("Wrong score: %d", score))
    case score < 60:
    	g = "F"
    case score < 80:
    	g = "C"
    case score < 90:
    	g = "B"
    case score <= 100:
    	g = "A"
    }
    return g
}
Copy the code

for

Write an integer to binary tree function

import (
	"fmt"
	"strconv"
)
func convertToBin(n int) string {
    res := ""
    for ; n > 0; n/=2 {
    	lsb := n % 2
    	res = strconv.Itoa(lsb) + res
    }
    return res
}
convertToBin(13) / / 1101
Copy the code

In addition. We don’t have while in go, we just use for, and we write a function that reads the file line by line.

import (
	"fmt"
	"os"
	"bufio"
)

func printFile(filename string) {
    file, err := os.Open(filename)
    iferr ! =nil {
    	panic(err)
    }
    
    scanner := bufio.NewScanner(file)
    
    for scanner.Scan() {
    	fmt.Println(scanner.Text())
    }
}
printFile("a.txt")
// lemon
// lemonfe
Copy the code

The function definitions

We have written many functions above, now let’s look at an example of a function that returns multiple values

func div(a, b int) (q, r int) {
    return a + b, a - b
}
q, r := div(1.2)
t, _ := div(3.4)
fmt.Println(q, r, t) // 3 -1 7
Copy the code

Why is _ used? Because go is not allowed to define variables without using them.

Multiple return values are usually used to return err.

func div(a, b int) (int, err){
    ...
}
Copy the code

A parameter is a function

package main

import (
	"fmt"
	"reflect"
	"runtime"
)

func add(a, b int) int {
    return a + b
}

func apply(op func(int.int) int.a.b int) int {
    // Get the function name
    p := reflect.ValueOf(op).Pointer() // Get the pointer to the function
    opName := runtime.FuncForPC(p).Name()
    fmt.Println(opName, a, b)
    return op(a, b)
}
func main(a) {
    fmt.Println(apply(add, 3.4))}Copy the code

Running results:

main.add 3 4
7
Copy the code

Variable argument list

func sum(nums ...int) int {
    s := 0
    for i := range nums {
    	s += nums[i]
    }
    return s
}
func main(a) {
    fmt.Println(sum(1.2.5.5.7.4))}Copy the code

Run result: 24

Pointer to the

var a int = 3
var pa *int = &a
*pa = 4
Copy the code
  • &a represents a pointer to the variable A
  • var pa *int = &aDeclare a pointer to a
  • *paIt’s just the value of A

Let’s implement a function that swaps the values of two variables:

func swap(a, b *int)  {
    *a, *b = *b, *a
}
func main(a) {
    a, b := 3.4
    swap(&a, &b)
    fmt.Println(a, b)
}
Copy the code

Running results:

4 3
Copy the code