Go语言基础学习

90 阅读3分钟

go语言基础

输入输出包:fmt

变量定义:

var 变量名=值
变量名 := 值
var 数组名 [长度]类型

切片: 使用make创建切片(应该类似vector,变长)

切片名 := make([]类型,长度)
追加元素 切片名 = append(切片名,追加的元素)
复制切片 copy(目标切片,被复制切片)

map:

使用make创建
map名 := make(map[key类型][value类型])
写入:
map名[key] = value
删除:
delete(map名, key)
查找
value, ok := map[key]
ok = 0则没有这个key

go语言只有for循环,条件判断类似c++,没括号 使用range遍历(类似python) for 索引,值 := range 切片

switch内置break,case里可以使用条件分支,可用来取代if else

函数:传入的是形参

func 函数名(参数1 参数类型,参数2 参数类型)(返回值1 返回值类型,返回值2 返回值类型)

结构体:

type 结构名 struct{
     变量名 类型
 }
 声明:
 变量名 := 结构名{初始化内容}
 结构体方法:
 func (名 结构名或结构指针) 函数名(变量)返回值
    

格式化输出 fmt.printf("%v",s) +v #v

json:结构体每个变量首字母大写(可以在结构体变量类型后加上小写变量名将其输出的标签变成小写)

使用json.Marshal(结构体)变成字节流,使用string打印字符串
json.Unmarshal(json变量,结构体指针)

os.Args返回运行参数 os.Getenv[]获取环境变量

exec.Command("grep", "127.0.0.1", "/etc/hosts").CombinedOutput() 执行grep命令,通过标准输出输出结果

输入输出:

输入:reader := bufio.NewReader(os.Stdin)
    input := reader.ReadString('\n')
    input = string.TrimSuffix(input,'\n')去掉行尾换行符
    或
    fmt.Scanf()//和C++类似
 

http:

client := &http.Client{}
req, err := http.NewRequeset("POST","url",data)
    response应该是对应响应的结构体
response,err := client.Do(req)
defer response.Body.close()//延迟关闭
bodyText, err := ioutil.Readall(response.Body)

bufio包:提供缓冲区读写

    reader := bufio.NewReader()
    reader.ReadByte()
    reader.Read(p []byte)一次性读取len(p)长度的数据
    

socket编程:

server,err := net.Listen("tcp","IP地址:端口")//监听端口
client,err := server.Accept() //接受请求
client.Write(字节流)将字节返回

go关键字运行一个goroutine

context:用于优雅的结束进程

type Context interface {

    Deadline() (deadline time.Time, ok bool) //返回当前context的截止时间

    Done() <-chan struct{} //当前任务取消时,将返回一个关闭的channel

    Err() error //如果Done返回的channel未关闭,则返回nil

    Value(key interface{}) interface{} //返回context存储的键值对中当前key的值
}
valuectx
type valueCtx struct {
    Context //父节点
    key, val interface{}
}

func (c *valueCtx) Value(key interface{}) interface{} {
    if c.key == key {
        return c.val
    }
    return c.Context.Value(key)
}

实现了Value方法,用于在context链路上获取key对应的值

cancelctx
type cancelCtx struct {
    Context //父节点

    mu       sync.Mutex            // protects following fields
    done     chan struct{}         // 一个channel,用来传递关闭信号,被第一个cancel函数关闭
    children map[canceler]struct{} // 一个map,存储当前节点下的所有子节点,cancelCtx其实也是canceler类型
    err      error                 // set to non-nil by the first cancel call
}

type canceler interface {
    cancel(removeFromParent bool, err error)
    Done() <-chan struct{}
}

使用WithCancel函数创建一个cancelCtx,返回一个contex和一个cancel函数,调用cancel函数即可执行cancel操作

使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(){
    ...
    cancel()
}
//监听子任务是否完成
<-ctx.Done()
return