Go language basics let you have a different feeling

The Go language is a statically strongly typed, compiled, concurrent, and garbage-collected programming language developed by Google. The Go language manages to reduce code complexity without compromising application performance.

The grammar of Go language is simple, with only 25 keywords, so we don’t need to spend a lot of time learning and memorizing;

G language data types include Boolean, numeric types (integer, floating point, complex), string, slice (array), dictionary map, pipeline chan, etc.

The Go language naturally has concurrency features. Based on the go keyword, it is easy to create a coroutine to perform some concurrent tasks. The CSP concurrent programming model based on the coroutine-pipeline, compared with the traditional complex multi-thread synchronization scheme, can It's too easy to say.

The Go language also has garbage collection capabilities, which avoids the need for the application layer to pay attention to memory allocation and release. 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.

Environment construction articles:

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 locally:

go1.19.darwin-amd64.tar.gz, this is the compiled executable file, just need to decompress it.

Unzip to directory:

$HOME/Documents/go1.18

Finally, configure the environment variables:

export GOROOT=$HOME/Documents/go1.18export PATH=$PATH:$GOROOT/binexport GOPATH=$HOME/Documents/gopath

GOROOT is the installation directory of Go; PATH is to allow us to execute the go command in any directory; the GOPATH working directory, the dependent packages downloaded through the go get command, etc. are placed in the GOPATH directory, and the dependent files based on gomod management will also be placed in this directory. Under contents.

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. It is recommended to use Goland. The download address is: https://www.jetbrains.com/go/

After the installation is complete, open the Goland new 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 in which they are located. As in the above "package main", we call it the main package. Of course, the package name can also be named 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 remain in other files, how to import it? Introduced by "import package name", the functions/variables in the package can only be accessed after introduction. 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 the standard output.

Data type articles:

Go language data types include Boolean, numeric types (integer, floating point, complex), string, slice (array), dictionary map, pipeline chan, etc. The declaration and simple use of variables of each type 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 the pipeline chan is not given here, which will be introduced in detail in the second chapter of the 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 later chapters.

Branch structure articles:

Similar to other languages, Go language also supports if/switch branch structure and 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 articles:

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). In addition, 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 very convenient to create coroutines to perform some concurrent tasks. The following program creates 10 coroutines to execute tasks concurrently, and the main coroutine waits for the execution of each sub-coroutine to finish, and then exits automatically:​​​​​​​​

package main
import (  "fmt"  "sync")
func main() {
   
       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 结束")}

Summarize

This article briefly introduces the basic grammar of the Go language, including basic concepts such as basic data types, branch structures, and functions, so that beginners can have a preliminary understanding of the Go language and lay the foundation for later advancement.

Guess you like

Origin blog.csdn.net/qq_24373725/article/details/128958713