1. 程式人生 > >Go常用功能總結一階段

Go常用功能總結一階段

sep format 字節數組 ngx str1 [] 構造函數 當前時間 mat

1. go語言從鍵盤獲取輸入內容

  <1. 最簡單的辦法是使用 fmt 包提供的 Scan 和 Sscan 開頭的函數。請看以下程序:

技術分享
package main
import "fmt"

var (
    firstName, lastName, s string
    i int
    f float32
    input = "56.12 / 5212 / Go"
    format = "%f / %d / %s"
)

func main() {
    fmt.Println("Please enter your full name: ")
    fmt.Scanln(&firstName, &lastName)
    fmt.Printf("Hi %s %s!\n", firstName, lastName)
    fmt.Sscanf(input, format, &f, &i, &s)
    fmt.Println("From the string we read: ", f, i, s)
}
技術分享

鍵盤輸入:liang yongxing,輸出結果如下所示:

1 2 Hi liang yongxing! From the string we read: 56.12 5212 Go

  Scanln 掃描來自標準輸入的文本,將空格分隔的值依次存放到後續的參數內,直到碰到換行。Scanf 與其類似,除了 Scanf 的第一個參數用作格式字符串,用來決定如何讀取。Sscan 和以 Sscan 開頭的函數則是從字符串讀取,除此之外,與 Scanf 相同。如果這些函數讀取到的結果與您預想的不同,您可以檢查成功讀入數據的個數和返回的錯誤。

  <2. 也可以使用 bufio

包提供的緩沖讀取(buffered reader)來讀取數據,正如以下例子所示:

技術分享
package main
import (
    "fmt"
    "bufio"
    "os"
)

var inputReader *bufio.Reader
var input string
var err error

func main() {
    inputReader = bufio.NewReader(os.Stdin)
    fmt.Println("Please enter some input: ")
    input, err = inputReader.ReadString(‘\n‘)
    if err == nil {
        fmt.Printf("The input was: %s\n", input)
    }
}
技術分享

  inputReader 是一個指向 bufio.Reader 的指針。inputReader := bufio.NewReader(os.Stdin) 這行代碼,將會創建一個讀取器,並將其與標準輸入綁定。

  bufio.NewReader() 構造函數的簽名為:func NewReader(rd io.Reader) *Reader

  該函數的實參可以是滿足 io.Reader 接口的任意對象,函數返回一個新的帶緩沖的 io.Reader 對象,它將從指定讀取器(例如 os.Stdin)讀取內容。返回的讀取器對象提供一個方法 ReadString(delim byte),該方法從輸入中讀取內容,直到碰到 delim指定的字符,然後將讀取到的內容連同 delim 字符一起放到緩沖區。

  ReadString 返回讀取到的字符串,如果碰到錯誤則返回 nil。如果它一直讀到文件結束,則返回讀取到的字符串和 io.EOF。如果讀取過程中沒有碰到 delim 字符,將返回錯誤 err != nil。在上面的例子中,我們會讀取鍵盤輸入,直到回車鍵(\n)被按下。

2. go語言字符串比較

  go語言中,判斷兩個字符串是否相等,用

1 strings.EqualFold(str1, str2)

  比較兩字符串

1 strings.Compare(a, b string) int

  判斷是否包含

1 strings.Contains(s, substr string) bool

  將數組按照指定的字符合並為字符串

1 strings.Join(a []string, sep string) string

  將字符串按照指定字符進行切割為數組

1 strings.Split(s, sep string) []string

   還有很多其他的,例如我們常用的轉位大寫、小寫、駝峰式;去掉空格、替換等,這些函數在go語言也都是存在的,如果需要請查看響應的文檔。

3. go語言獲取時間

 1. 獲取當前時間時間戳

1 2 fmt.Println(time.Now().Unix()) # 1492506479

 如果想要獲取精確到毫秒級別的時間戳即精確到 13 位,Go 語言中沒有直接的方法,可以使用得到納秒級別的時間戳,之後除以 1000000 之後得到毫秒級別,即如下代碼:

1 time.Now().UnixNano() / 1000000

 2. 獲取當前標準時間,格式:yyyy-MM-dd HH:mm:ss

1 2 fmt.Println(time.Now().Format("2006-01-02 15:04:05")) // 這是個奇葩,必須是這個時間點, 據說是go誕生之日, 記憶方法:6-1-2-3-4-5 # 2017-04-18 17:10:25

 3. 時間戳轉str格式的時間

1 2 3 str_time := time.Unix(1389058332, 0).Format("2006-01-02 15:04:05") fmt.Println(str_time) # 2017-04-18 17:10:25

 4. str格式時間轉時間戳

1 2 3 4 5 6 the_time, err := time.Parse("2006-01-02 15:04:05", "2017-04-18 17:10:25") if err == nil { unix_time := the_time.Unix() fmt.Println(unix_time) } # 1492506479

4. golang 中的緩沖應用

  bytes.buffer是一個緩沖byte類型的緩沖器存放著都是byte。Buffer 是 bytes 包中的一個結構體: type Buffer struct{…}

  底層原理:其實底層就是一個 []byte, 字節切片

  創建 Buffer緩沖器的幾種方式:

  1. 初始化應用

  var buffer bytes.Buffer                // 直接定義一個 Buffer 變量,而不用初始化
  buffer.Writer([]byte("Hello World!"))  // 可以直接使用

  2. 使用 new 初始化

  buffer := new(bytes.Buffer)     //直接使用 new 初始化,可以直接使用 

  3. 傳入字節數組創建

  buffer := NewBuffer([]byte{"hello"})

  4. 傳入字符串創建

  buffer := bytes.NewBufferString("helloWorld")

  Buffer既可以被讀也可以被寫。如果是讀Buffer,buf需填充一定的數據;如果是寫,buf需有一定的容量(capacity),當然也可以通過new(Buffer)來初始化Buffer。另外一個方法NewBufferString用一個string來初始化可讀Buffer,並用string的內容填充Buffer.

技術分享
import (
    "bytes"
    "fmt"
    "testing"
)

func TestBufferString(t *testing.T){
    buf1:=bytes.NewBufferString("swift")
    buf2:=bytes.NewBuffer([]byte("swift"))
    buf3:=bytes.NewBuffer([]byte{‘s‘, ‘w‘, ‘i‘, ‘f‘, ‘t‘})
    fmt.Println("===========以下buf1,buf2,buf3等效=========")
    fmt.Println("buf1", buf1)
    fmt.Println("buf1", buf2)
    fmt.Println("buf1", buf3)
    fmt.Println("===========以下創建空的緩沖器等效=========")
    buf4:=bytes.NewBufferString("")
    buf5:=bytes.NewBuffer([]byte{})
    fmt.Println("buf4:", buf4)
    fmt.Println("buf5:", buf5)
}
技術分享

運行結果如下:

技術分享
===========以下buf1,buf2,buf3等效=========
buf1 swift
buf1 swift
buf1 swift
===========以下創建空的緩沖器等效=========
buf4: 
buf5: 
技術分享

寫入數據的三種方式:

技術分享
//write string
buffer.WriteString("abc")
//write []byte
buffer.Write([]byte("abc"))
buffer.Write(byte{‘a‘, ‘b‘, ‘c‘})
//write byte
buffer.WriteByte(‘c‘)
技術分享

5. 接口轉換為字符串即interface{}-->string

var a interface{}
var b string = a.(string)

  其中 b 就是通過接口 a 轉換而來。

5. string、int、int64相互轉化

技術分享
#string --> int  
int,err:=strconv.Atoi(string)  

#string --> int64  
int64, err := strconv.ParseInt(string, 10, 64)  

#int --> string  
string:=strconv.Itoa(int)  

#int64 --> string  
string:=strconv.FormatInt(int64,10)

Go常用功能總結一階段