Go碎碎念

1. 时间类型转换为字符串类型

    now := time.Now()

    fmt.Println(now.Format("2006-01-02 03:04:05 PM"))

    yesterday := time.Now().AddDate(0,0,-1).Format("2006-01-02")

2. go如何执行外部命令

package main

import (
        "fmt"
        "os/exec"
        "strings"
)

const (
    cpuNumCmd = "grep 'processor' /proc/cpuinfo | sort -u | wc -l"
    memSizeCmd = "grep 'MemTotal' /proc/meminfo |awk '{print $2/1024}'"
)

func main(){
      cpuNum := execShell(cpuNumCmd)
      fmt.Println(cpuNum)
      memSize := execShell(memSizeCmd)
      fmt.Println(memSize)
}


func execShell(cmd string) string {
        out, err := exec.Command("bash","-c",cmd).Output()
        if err != nil {
                return fmt.Sprintf("Failed to execute command: %s", cmd)
        }
        return strings.Replace(string(out),"\n","",-1)
}

3. go中如何将字符串分割成数组(分隔符为一个或多个空格)

     re, _ := regexp.Compile(" +") 

     re.Split(v,n)

     其中,n代表分割的次数,如果为负数,则代表切割任意次。

4.  ./3.go:51:34: cannot use example["query"] (type interface {}) as type string in assignment: need type assertion

for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

5. 数组和切片的区别

   其实两者的定义差不多,只不过前者需要指定长度,而后者则不需要,如:

   数组: var a [3]int

   切片: var s []int

   切片也可通过make创建

   var s = make([]int,0)

6. 如何判断某一行是否为空行

    if  (len(line) ==0) 

7. 如何去掉字符串中的一个或多个空格

strings.Join(strings.Fields(str),"")

posted @ 2017-12-29 18:29  iVictor  阅读(300)  评论(0编辑  收藏  举报