golang基本用法速查

2020-02-11  本文已影响0人  wildsre

Hello World!

package main

import "fmt"

func main() {
   fmt.Println("Hello World!") 
}

引入模块

引入内置模块

//单个引入
import "fmt"

//引入多少个
import (
    "fmt"
    "os"
)

引入第三方模块

import (
    "github.com/wildsre/arc/arc"
    arcModel "github.com/wildsre/arc/model"
    "github.com/wildsre/arc/router"
)

变量初始化

基本变量初始化

    var x int
    var (
        i int
        j float64
        k, z string
    )
    v := "test"

数组&切片初始化

初始化后, 长度和容量都相等, 数组初始化完后就已经分配所有长度的内存, 切片在使用append扩容后, cap会与len不等

    //初始化定长数组
    arr := [3]int{1,23} //len: 3, cap: 3 
    s := []int{1,3}     //len:2, cap:2
    //初始化定长切片
    slice := make([]int, 3)

映射初始化

    //方式1: 先声明, 后赋值, 声明后m为nil指针
    var m map[string]string
    m = make(map[string]string)
    m["k1"] = "v1"
    //方式2
    m2 := map[string]string{"k1":"v1", "k2":"v2"}
    m2 := map[string][]int{"k1":{1,2}, "k2":{1,1}}
    m3 := map[string]map[string]string{"k1":{"k11":"v1"}}

结构体初始化

    //匿名结构体
    s1 := struct {
        Att1 string
        Att2 int
    }{"a", 1}

    //先定义再初始化
    type Foo struct {
        A1 string
        A2 []int
    }

    //初始化需要注意, 前后括行不能为空 
    // Foo:{
    //    "a", 
    //    []int{1,2} 
    // } 会报错
    s2 := Foo{ "a",
        []int{1,3} }

    //初始化部分变量
    s3 := Foo{ A1: "s" }

控制语句

循环

    for i:=0; i<2; i++ {
        fmt.Println(i)
    }

判断

    if i<0 {
        fmt.Println("one")
    } else if i>=0 && i<3 {
        fmt.Println("two")
    } else {
        fmt.Println("three")
    }

数据类型转换

string 和 bytes

    s1 := "test 测试"
    //string to bytes
    b1 := []byte(s1)

    //bytes to string
    s2 := string(b1)

string 和 数字

    import "strconv"
    s1 := "2001"
    //string to int
    i1, e := strconv.Atoi(s1)
    
    //int to string
    s2 := strconv.Itoa(i1)

    s3 := "3.1415"
    //string to float
    f1, e := strconv.ParseFloat(s3, 64)

    //float to string
    s4 := fmt.Sprintf("%.3f", f1)

json 的处理

import "encoding/json"

type UserData struct {
    UserName string `json:"username"`
    Token string `json:"token"`
    DefaultSpace string `json:"default-space"`
    Space map[string]string `json:"space"`
}

txt := `{
    "username":"foo", 
    "token": "a123", 
    "default-space": "foo", 
    "space": {"foo":"bar"}
}`
ud := new(UserData)

//json字符串转对象, 参数2需要为指针
e := json.Unmarshal([]byte(txt), ud)

//对象转json字符串
txt2, e := json.Marshal(ud)

时间-日期处理

    import "time"

    //获取当前时间, Time结构体
    now := time.Now()

    //格式化时间, layout只能为固定格式
    fnow := now.Format("2006-01-02 15:04:05.000")
    fmt.Println(fnow)

    //时间戳(秒,纳秒)
    fmt.Println(now.Unix())
    fmt.Println(now.UnixNano())

    //解析时间字符串, 时区?
    last, e := time.Parse("2006-01-02T15:04:05.000", "2020-02-29T15:33:40.312")
    fmt.Println(last, e)

    //时间运算: 5分钟前(毫秒到小时: ms, s, m, h)
    d5, _ := time.ParseDuration("-5h")
    last5 := last.Add(d5)
    fmt.Println(last, last5)

    //时间运算: 两时间差
    d2 := now.Sub(last)
    fmt.Println(d2.String())
//时间格式
const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
    // Handy time stamps.
    Stamp      = "Jan _2 15:04:05"
    StampMilli = "Jan _2 15:04:05.000"
    StampMicro = "Jan _2 15:04:05.000000"
    StampNano  = "Jan _2 15:04:05.000000000"
)

文件读写

https://www.jianshu.com/p/7790ca1bc8f6

import (
    "os"
    "ioutil"
)

读文件

const (
        // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
        O_RDONLY int = syscall.O_RDONLY // open the file read-only.
        O_WRONLY int = syscall.O_WRONLY // open the file write-only.
        O_RDWR   int = syscall.O_RDWR   // open the file read-write.
        O_APPEND int = syscall.O_APPEND // append data to the file when writing.
        O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
        ...
)
//               文件名      模式                               权限
f := os.OpenFile("test.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)

//f.Read([]byte), Read方法读取指定长度的字节, 一般我们会读取被打开文件的所有内容
//使用 ioutil.ReadAll 获取全部内容
//使用 ReadAll 接口要求参数 f 需要有 Read(b []byte) (n int, err error) 接口
txt, err := ioutil.ReadAll(f)

//只读取文件
txt, err := ioutil.ReadFile("test.txt")

写文件

f.Write([]byte("hello."))

压缩-解压gzip文件例子

import (
    "os"
    "io/ioutil"
    "compress/gzip"
)
//使用gzip压缩二进制文件
srcBin, err := ioutil.ReadFile("test.bin")
dstGz, err := os.OpenFile("test.gz", os.O_CREATE|os.O_WRONLY, 0644)
gzHandle := gzip.NewWriter(dstGz)
gzHandle.Write(srcBin)
//解压gzip文件
srcGz, err := os.Open("test.gz")
dstBin, err := os.Open("test.bin", os.O_CREATE|os.O_WRONLY, 0755)
gzHandle, err := gzip.NewReader(srcGz)
content, err := ioutil.ReadAll(gzHandle)
dstBin.Write(content)

函数

协程

上一篇下一篇

猜你喜欢

热点阅读