string

参考: The Go Programming Language Specification - String

crude string(raw string)

语法: 通过“`”backquote,定义。 功能:

  • 禁止转义 escape,“\” 在``内部无特殊意义
  • 允许换行
  • "\r" 被自动舍弃

使用场景:

  • 正则
  • 多行 string

eg:

1
2
3
name string `that is "name"`

second_name string "that is \"second name\""

转义字符

  • \nnn : 3 位八进制, eg: \123
  • \xnn : 2 位 16 进制, eg: \x2a
  • unicode:

    • \uNNNN : 4 位 16 进制
    • \UNNNNNNNN : 8 位 16 进制

gopath goroot gobin 辨析

  1. 查看命令

    1
    
    go env
    GOBIN=""
    GOPATH="/home/sawyer/go"
    GOROOT="/usr/lib/go"
    

golang 模块和包

参考: 理解Golang包的import导入机制_CodingPassion 的博客-CSDN博客_go import原理

同一包内部的函数等,不用导入

file: increase.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package main

import (
    // "fmt"
)

func Increase (a int) int {
    a += 1
    return a
}

file: main.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
    // "fmt"
    // "./main/increase"
    // "rsc.io/quote"
)

func main() {
    const pi =3.14

    println(pi)
    println(3);

    println(Increase(3))
}

go mirrors

参考: aliyun goproxy

1
export GOPROXY=https://mirrors.aliyun.com/goproxy/

module 和 依赖处理

参考: Managing dependencies - The Go Programming Language

module 命名风格

<prefix>/<descriptive-text>

prefix:

  • 两种方式

    • github.com/<progject|user>

      • 用户公开的 module
    • 其他自定义

      • 公司名
      • 项目名(包含其它小项目的大项目名称)
  • 禁用 prefix

    • test
    • example
    • example.com

依赖声明文件 go.mod

参考: go.mod file reference - The Go Programming Language

通过 require 语句指定依赖的 module 。

生成方法:

  • 自动生成

    • go mod tidy

      • 根据 golang 源代码自动生成

举例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#当前项目的 module 名称
module example.com/mymodule

# 当前 module 支持的最小 golang 版本
go 1.14

# 依赖的其它 module
require (
    example.com/othermodule v1.2.3
    example.com/thismodule v1.2.3
    example.com/thatmodule v1.2.3
)

replace example.com/thatmodule => ../thatmodule
exclude example.com/thismodule v1.3.0

依赖 module version 格式

  • v1.3.0
  • v0.0.0-20200921210052-fa0125251cc4

    • 对于 git repo 没有 tag version, golang tools 自动生成的 version

替换依赖的 module (replace 指令)

参考: go.mod file reference - Replace Directive

replace module-path [module-version] => replacement-path [replacement-version]

举例:

1
2
3
require example.com/othermodule v1.2.3

replace example.com/othermodule => example.com/myfork/othermodule v1.2.3-fixed
  • 替换所有版本
1
2
3
require example.com/othermodule v1.2.3

replace example.com/othermodule => ../othermodule
  • 替换指定版本
1
2
3
require example.com/othermodule v1.2.5

replace example.com/othermodule v1.2.5 => ../othermodule

发现依赖更新

go list -m -u all
go list -m -u my/module
  • -m : 发现 module, go list 默认列举的是 package
  • -u : upgradable

添加依赖

go get .
  • 添加当前 package 中的所有依赖 module 到 go.mod 文件
go get <my/module>
  • 添加指定 module 到 go.mod 文件

升级依赖

go get <my/module>@version