Go language is a static strongly typed, compiled, concurrent programming language developed by Google with garbage collection function. The Go language achieves a reduction in code complexity without sacrificing application performance.
Go language syntax is simple, only 25 keywords, no need to spend time to learn and memorize; data types include boolean, numeric types (integer, floating point, complex number), string, slice (array), dictionary map, pipeline chan, etc., it is relatively smooth to use.
The Go language naturally has concurrency features. Based on the go keyword, it is easy to create coroutines to perform some concurrent tasks. The CSP concurrent programming model based on coroutine-pipeline, compared with the traditional complex multi-threaded synchronization scheme, can It's too simple to say.
The Go language also has garbage collection capabilities, which avoids the need for the application layer to pay attention to the allocation and release of memory. You must know that in the C/C++ language, memory management is very troublesome.
The Go language also provides a relatively complete standard library. For example, we only need a few lines of code to create and start an HTTP service.
Starting from this article, it will lead you into the world of Go language.
Environment construction
We can choose to download the source code to compile and install, download the installation package to install, and download the compiled executable file. The download address is: https://golang.google.cn/dl/
The author installed go1.18.darwin-amd64.tar.gz locally. This is the compiled executable file. It only needs to be decompressed and decompressed to the directory $HOME/Documents/go1.18. Finally, configure the environment variables:
export GOROOT=$HOME/Documents/go1.18
export PATH=$PATH:$GOROOT/bin
export GOPATH=$HOME/Documents/gopath
$GOROOT is the installation directory of Go; $PATH is to allow us to execute the go command in any directory; $GOPATH working directory, the dependency packages downloaded through the go get command, etc. are placed in the $GOPATH directory, and the dependency files managed by gomod are also will be placed in this directory.
After the installation configuration is complete, execute go version to verify whether the installation is successful.
A suitable editor is indispensable for Go project development. Goland is recommended. The download address is: https://www.jetbrains.com/go/ . After the installation is complete, open the new Goland project, create a new main.go file, and write the classic hello world:
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
All files in the Go language must specify the package where they are located, such as "package main" above, we call it the main package, of course, the package name can also be named with other names (generally the package name is consistent with the current directory/folder name), The main function in the main package is the entry function of the program.
Our code will definitely still be other files, how to introduce it? Imported by "import package name", the functions/variables in the package can be accessed only after the import. As shown in the above code, the fmt package is a formatting/IO package provided by the bottom layer of the Go language, and the Println function prints variables to standard output.
type of data
Go language data types include Boolean, numeric types (integer, floating-point, complex), strings, slices (arrays), dictionary map, pipeline chan, etc. The declaration and simple use of various types of variables are as follows:
package main
import "fmt"
func main() {
//变量声明
var a int = 1 //var 声明并初始化变量, 类型int可以省略
b := 1 //:= 声明+初始化变量
b = 3 //=只能针对已有变量重新赋值
fmt.Println(a, b)
//字符串
str1 := "hello "
str2 := "world"
fmt.Println(len(str1), str1 + str2) //可以 +;len返回字符串长度
//数组,容量固定
arr := [5]int{1,2,3,4,5}
arr[1] = 100 //数组元素访问
fmt.Println(len(arr), arr) //len返回数组长度
//切片,容量可以扩充,相当于动态数组
slice := []int{1,2,3}
slice[1] = 100 //切片元素访问
slice = append(slice, 4, 5, 6) //append自动扩容
fmt.Println(len(slice),cap(slice), slice) //len返回切片长度,cap返回切片容量
//map,key-value结构
score := map[string]int{
"zhangsan":100,
"lisi":99,
"wangwu":98,
}
score["who"] = 90 //map赋值
s, ok := score["who"] //map访问,s对应value值,ok标识该key是否存在(不存在返回空值)
delete(score, "lisi") //删除map元素
fmt.Println(s, ok, score)
}
The example of pipeline chan is not given here, which will be introduced in detail in Chapter 2 Concurrency Model. Of course, in addition to these basic types provided by the Go language, we can also customize types, such as interfaces, structures, etc., which will also be introduced in the following chapters.
branch structure
Similar to other languages, Go language also supports if/switch branch structure, for loop structure, as shown below:
package main
import "fmt"
func main() {
//if分支
condition := true
if condition {
fmt.Println("true")
}else{
fmt.Println("false")
}
//wsith分支
expr := "zhangsan"
switch expr {
case "zhangsan":
fmt.Println("zhangsan")
case "lisi":
fmt.Println("lisi")
default: //没有匹配到,默认执行
fmt.Println("who")
}
//for循环
for i := 0; i < 100; i ++ {
if i /2 == 0 {
fmt.Println("偶数")
}
}
//无条件循环,死循环
i := 0
for {
i ++
fmt.Println("loop")
if i > 100 { //检测条件,提前break退出循环
break
}
}
}
function
The definition of functions, such as name, input parameters, return value and other basic concepts will not be introduced here. The difference between Go language and other languages is that it supports multiple return values (most languages can only return one value), And variable parameters (most languages actually support it), and the Go language also supports closures (anonymous functions). Examples are as follows:
package main
import "fmt"
func main() {
add, sub := addSub(4, 3)
fmt.Println(add, sub)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...) //切片转可变参数,通过...实现
//变量f为函数类型
f := func (in string) {
fmt.Println(in)
}
f("hello world") //执行函数
//声明匿名函数,注意与上面却别,加括号直接执行该匿名函数
func (in string) {
fmt.Println(in)
}("hello world")
}
//返回两个int值
func addSub(a, b int) (int, int){
return a + b, a - b
}
//...表示参数数目可变
func sum(nums ...int) {
total := 0
//nums其实是切片类型([]int),for + range 可遍历切片元素
for _, num := range nums {
total += num
}
fmt.Println(total)
}
Coroutine Concurrency
The Go language naturally has concurrency features. Based on the go keyword, it is easy to create coroutines to perform some concurrent tasks. The following program creates 10 coroutines to execute tasks concurrently. The main coroutine waits for the completion of the execution of each sub-coroutine, and then automatically exits:
package main
import (
"fmt"
"sync"
)
func main() {
//WaitGroup用于协程并发控制
wg := sync.WaitGroup{}
//启动10个协程并发执行任务
for i := 0; i < 10; i ++ {
//标记任务开始
wg.Add(1)
go func(a int) {
fmt.Println(fmt.Sprintf("work %d exec", a))
//标记任务结束
wg.Done()
}(i)
}
//主协程等待任务结束
wg.Wait()
fmt.Println("main end")
}
Summarize
This article is the first in a series of in-depth understanding of the Go language. It briefly introduces the basic syntax of the Go language, including basic data types, branch structures, functions and other basic concepts. It aims to give you a preliminary understanding of the Go language. From the next article To get started, we'll start a full exploration of the Go language.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。