Golang learning course - continually updated

Learning a language first hello world

1, first create a directory, create a file hello.go

package main

import (
   "fmt"
)

func main()  {
   fmt.Println("hello world")
}

2,go run hello.go


jack_zhou@zhoulideMacBook-Pro study % go run hello.go
hello world


Above we completed our basic mission. Here we officially get started

Before officially entering the write code, we recommend using Goland JB family

In Settings need to pay attention GOPATH and GOROOT can not write to the same address, otherwise it will error:

warning: GOPATH set to GOROOT (/usr/local/go) has no effect

First, Beginners

1, golang language features

① Garbage Collection

  1. Automatic memory recovery does not require developers to manage memory
  2. Developers only need to focus on business implementation, reduce the burden
  3. Just new to allocate memory, no release

② natural concurrency

  1. From the linguistic level support concurrency, very simple
  2. goroute, lightweight threads, create thousands of possible goroute
  3. CSP (Communicating Sequential Process) model implementation based on

③ duct (channel)

  1. Pipe, similar to the unix / linux in the pipe
  2. Between a plurality of communication through the channel goroute
  3. Support any type

④ multi-value return

  1. Defined function return types require parentheses
  2. Need to be returned, as the separator

⑤ needs to be compiled

go build + path

2, the variable definition:

# 第一种package变量
var (
    a = 1
    b = 2
)
var aa = true

# 第二种非package变量
var a, b int = 1, 2
# 简写
var a,b = 1, "89"
# 精简
a, b := 1, "78"  // 全局不可使用

In addition a write function on the basis of an example, the incoming two variables, and returns the two parameters

package main

import (
    "fmt"
)

func add(a int, b int) int {
    var sum int 
    sum = a + b
    return sum

}

func main()  {
    var c int
    c = add(100, 200)
    fmt.Println("hello world!", c)
}

In the above example, we can see that he is no title of

Need to specify the ratio of the variable type when the variable is defined, when defining the function, the () on the outside need to write the return value of type

It should be noted that the situation can not go without the use of variable Xu Dingyi happen, otherwise it will compile time error, such as:


c declared and not used


3, the definition of the package

  • And Python language, the same function code into a directory called package (Therefore, when writing code are required to write package package name)
  • Of course, the package of support being referenced by other packages
  • main packet is used to generate an executable file, each program has one and only one main packet
  • The main purpose is to improve the package code reusability

4 Notes

When ① Go be build often encounter can not load package

In the configuration in Goland

You need to add Project GOPATH path

② Go under the new project is required by default src, and, when not required to compile src write path

go by default all project files are placed in src directory

Execution go build go_test / day1 / example in the project directory can be

③ generally build files are specified in a bin directory

go build -o bin/calc go_dev/day1/package_count/main

Use -o to specify the directory bin, files calc, is the main compiler

5 basic types of go

① file identifier name & keyword &

  • [X] to all source end .go

  • [X] identifiers beginning letters or underscore, case sensitive (_)

  • [X] _ is a special identifier, to ignore the results

  • [X] reserved keyword

    break default func interface select
    case defer go map struct
    chan else goto package switch
    const fallthrough if range type
    continue for import return where

The basic structure of the program ② Go

  1. Any code that is part of a package file

  2. import keywords, references to other packages

    import ("fmt")
    import ("os")
    // 通常写为
    import (
     "fmt"
      "os"
    )
  3. Golang executable program, package main, and the main function and only one inlet

  4. The bag function calls, direct calls

  5. Call functions within different packages, the package needs to be called by name + dot + function name (function name first letter must be uppercase)

    package main
    
    import "fmt"
    
    func list(n int) {
       for i := 0; i <= n; i++ {
          fmt.Println("%d+%d=%d\n", i, n-i, n)
       }
    }
    func main() {
       list(10)
    }
    // 打印循环
  • [X] Note: in the packet may define an init function, default execution performed before main

    package calc
    
    var Name string = "jack"
    var Age int = 10
    
    func init() {
       Name = "zhou"
       Age = 100
    }
    // 最终结果是Name为zhou,Age为100
    // 执行顺序 先执行全局变量,在执行init,最后到main

③ constants and variables

First, the constant

  1. 常量使用const修饰,代表永远是只读的,运行期间不能够修改

  2. const只能修饰boolean,number(int相关类型、浮点类型、cpmplex)和string

  3. 语法:const identifier [type] = value,其中type可以省略。

    const b string = "hello world"
    const b = "hello world"
    const Pi = 3.1415926
    const a = 9.3
    const c = getValue() // 错误,因为常量是不可改变的
  4. 单行注释 // 多行注释 /* */(其实和JS的写法一致的)

二,变量

见上方变量的定义

④ 数据类型和操作符

一,数据类型

值类型: 基本数据类型int,float, bool, string以及数组和struct

当值类型需要修改的时候 传入值之前加一个&即可,比如:

modify(a) ---->>> modify(&a)

这样就相当于传入a的内存地址到modify中去

引用类型: 指针,slice,map, chan等都是引用类型

二,操作符

  1. 逻辑操作符

    == 、!=、<=、>=、>、<、!、&&、 ||

    func main() {
       a := 10
       if (a > 2) {
          fmt.Println(a)
       }
    }
  2. 数学操作符

    +、-、*、/ 等等

⑤ 字符串类型

func main()  {
   var str = "hello world\n"
   var str1 = `
        窗前明月光,
      地上鞋两双。
      `
   var b byte = 'c'
   fmt.Println(str)
   fmt.Println(str1)
   fmt.Println(b)
   fmt.Printf("%c\n", b)
}

go在进行输出的时候是不会改变原有的样式的,对于打印bytes对象,会直接打印对于字符表中的具体位置的

fmt文档:给您放这里啦

例子: 交换两个变量的值

package main

import (
   "fmt"
   _ "os"
)

func swap(a int, b int) {
   tem := a
   a = b
   b = tem
   return
}

func main() {
   first := 100
   second := 200
   swap(first, second)
   fmt.Println(first, second)
}

结果如下:

jack_zhou@zhoulideMacBook-Pro ~ % /Users/jack_zhou/workspace/gospace/project/main ; exit;

100 200


为啥没有产生变化呢?

因为这两个变量属于值类型的,值类型是属于复制拷贝,改的是副本的值,如果需要改就必须传入指针地址。那如何修改呢?

package main

import (
   "fmt"
   _ "os"
)

func swap(a *int, b *int) {
   tem := *a
   *a = *b
   *b = tem
   return
}

func main() {
   first := 100
   second := 200
   swap(&first, &second)  // 传入变量的地址
   fmt.Println(first, second)
}

结果如下:

Last login: Sun Dec 8 22:55:57 on ttys002

jack_zhou@zhoulideMacBook-Pro ~ % /Users/jack_zhou/workspace/gospace/project/main ; exit;

200 100


package main

import (
   "fmt"
   _ "os"
)

func swap(a int, b int) (int, int) {
   tem := a
   a = b
   b = tem
   return a, b
}

func main() {
   first := 100
   second := 200
   first, second = swap(first, second)  // 传入变量的地址
   fmt.Println(first, second)
}

通过返回值的方式也是可以的

最简单的方式是:

package main

import (
   "fmt"
   _ "os"
)

func main() {
   first := 100
   second := 200
   first, second = second, first
   fmt.Println(first, second)
}

写到这突然发现还是Python大法好啊╮( ̄▽ ̄)╭

⑥ 字符串的操作

  1. 直接相加

    package main
    
    import "fmt"
    
    func main()  {
       var str = "hello"
       var str2 = " world"
       str3 := str+str2
       fmt.Println(str3)
    }
  2. 格式化输出

package main

import "fmt"

func main() {
   var str = "hello"
   var str2 = " world"
   // str3 := str+str2
   str3 := fmt.Sprintf("%s %s", str, str2) // 格式化输出
   fmt.Println(str3)
}
  1. 求字符串长度

    package main
    
    import "fmt"
    
    func main() {
       var str = "hello"
       var str2 = " world"
       // str3 := str+str2
       str3 := fmt.Sprintf("%s %s", str, str2) // 格式化输出
       n := len(str3)
       fmt.Printf("len(str)=%d\n", n)
    }
  2. 字符串的切片

    package main
    
    import "fmt"
    
    func main() {
       var str = "hello"
       var str2 = " world"
       // str3 := str+str2
       str3 := fmt.Sprintf("%s %s", str, str2) // 格式化输出
       substr := str3[0:5] // 和Python操作一致
       fmt.Println(substr)
    }
  3. 字符串反转

    package main
    
    import "fmt"
    
    func reverse(str string) string {
       var result []byte
       tmp := []byte(str) // 强制转换字符数组
       length := len(str)
       for i := 0; i < length; i++ {
          result = append(result, tmp[length-i-1])
       }
       return string(result)
    }
    func main() {
       var str = "hello"
       var str2 = " world"
       str3 := str + str2
       result := reverse(str3)
       fmt.Println(result)
    }

Guess you like

Origin www.cnblogs.com/zhoulixiansen/p/12014323.html