Golang introduction to minimalism (part 1) : basic concepts

  • 2020-05-07 19:53:01
  • OfStack

installs Golang

In http: / / golang org dl/can download to Golang. Installation documentation: http: / / golang org/doc/install.

Hello Go

Let's first create a file hello.go:


package main
 
import "fmt"
 
func main() {
    fmt.Printf("hello Golang\n");
}

Execute this program:


go run hello.go

package

The Golang program consists of a package (packages), which runs from the main package:


package main

This statement indicates that the file belongs to the main package (multiple source files can belong to the same package). The import statement is followed by the path where the package is located (called the package path or the import path), and one package is placed in one directory. The usual practice is that the directory name is the same as the package name:


import (
    "fmt"
    "math/rand"
)

Here "fmt" and "math/rand" are package paths (import paths). The import statement above could also read:


import "fmt"
import "math/rand"

After we import the package, we can refer to the exported name by "package name.name", for example:


import "fmt"
 
// fmt Package is deduced Printf
fmt.Printf("hello Golang\n");

In Golang, if the first letter of a name is capitalized, the name is exported.

function


package main
 
import "fmt"
 
func add(x int, y int) int {
    return x + y
}
 
func main() {
    fmt.Println(add(42, 13))
}

The important thing to note is that the variable name comes before the type, which is different from many languages. In addition, x int, y int can also be written as x, y int:

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

Function can return multiple values:


package main
 
import "fmt"
 
func swap(x, y string) (string, string) {
    return y, x
}
 
func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

The return value can be specified by the variable name and used as variable 1:


package main
 
import "fmt"
 
func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}
 
func main() {
    fmt.Println(split(17))
}

You can see that the split function USES the return statement directly without taking arguments.

variable

Variables are declared using the var statement:


go run hello.go
0

Variables can be initialized when declared:


go run hello.go
1

We saw that you can specify the variable type or not at the time of initialization.
According to the syntax of Golang, any structure outside the function (construct) starts with a keyword, such as the variable starts with the var keyword and the function starts with the func keyword. Within functions, variable assignments can be made using the := operator:


package main
 
func main() {
    var x, y int = 1, 2
    i, j := true, "hello"
}

The left side of the operator is the variable and the right side is the value.

data type

Basic data type:

1.bool
2.string
3.int int8 int16 int32 int64
4.uint uint8 uint16 uint32 uint64
5.uintptr
6.byte (equivalent to uint8)
7.rune (equivalent to int32, used to represent 1 unicode code point)
8.float32 float64
9.complex64 complex128

Type conversion USES the expression T(v), which means to convert v to type T:


var i int = 42
var f float64 = float64(i)
 
i := 42
f := float64(i)

Type conversions always need to be done explicitly.

Use const to declare constants:


go run hello.go
4

control statement

for statement

Golang USES (and only USES) for for looping (no while statement) :


go run hello.go
5

Unlike languages such as C/C++, for statements are not required () and {} is required (if and switch are also required in this syntax). If an infinite loop is required, use:


go run hello.go
6

if statement

The if statement can carry one statement before executing the conditional judgment (this is often called if with one phrase), and the life cycle of the variable in this statement ends after the if statement. Such as:


go run hello.go
7

switch


go run hello.go
8

Unlike languages such as C/C++, Golang does not use break statements to jump out of switch. In addition, switch can have no conditions:


go run hello.go
9

defer

An defer statement can add a function call to a list (this function call is called an deferred function call) and call the function in the list at the end of the current function call. Example:


package main
0

deferred function calls are executed in the order of first and last:


package main
 
import "fmt"
 
func main() {
    for i := 0; i < 5; i++ {
        // The output 43210
        defer fmt.Print(i)
    }
}

structure (structs)

Structure is a set of 1 domain:


package main
 
import "fmt"
 
type Vertex struct {
    X int
    Y int
}
 
func main() {
    v := Vertex{1, 2}
    v.X = 4
    fmt.Println(v)
}

Pointers exist in Golang, but Pointers do not support arithmetic operations:


p := Vertex{1, 2} // {1, 2} for struct literal
q := &p // q A type of *Vertex
q.X = 2 // Direct access domain X

As seen above, literal of struct is wrapped in {}. In struct literal we can use the syntax Name: to set the value for a particular field:


type Vertex struct {
    X, Y int
}
 
r := Vertex{X: 3} // At this time Y for 0

new function

We can assign a value of type T to be initialized to 0 by the expression new(T) and return a pointer to the value as follows:


var p *T = new(T)
p := new(T)

More detailed examples:


package main
 
import "fmt"
 
type Vertex struct {
    X, Y int
}
 
func main() {
    v := new(Vertex)
    fmt.Println(v)
    v.X, v.Y = 11, 9
    fmt.Println(v)
}

array and slice

[n]T is a type in Golang (just like *T 1), indicating that an array of length n has an element type of T. Example:


package main
7

Note that the array length cannot be changed.

slice is a data structure that points to a contiguous part of an array. slice works like an array. []T is of type slice, where the element type is T:


package main
8

The expression s[lo:hi] is used to create an slice. The newly created slice element is the element of the [lo, hi) position in s.

Create slice using the make function (instead of the new function, because additional parameters need to be set to control the creation of slice) :


// len(a) for 5
a := make([]int, 5)

Here the make function creates an array (whose elements are initialized to 0) and returns an slice pointing to the array. make can take a third parameter to specify the capacity:


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

An slice with no value is nil, with both length and capacity 0.


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

range

range is used in for to iterate over 1 slice or 1 map:


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

map

map is used to map key to value (value). map can be created with make (not new) :


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

map iteral is a lot like struct literal:


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

Use [] to access values in map and delete to delete values in map:


import (
    "fmt"
    "math/rand"
)
5
If it is necessary to check whether an key in map is in use:

import (
    "fmt"
    "math/rand"
)
6
elem indicates the value of key (elem is 0 if key does not exist) and ok indicates whether key exists.

closure

The function in Golang is also 1 value (just like the value in int), and the function can be 1 closure. A closure is a function that references an external variable. Here's an example:


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


Related articles: