美文网首页
Golang Tips

Golang Tips

作者: Lyudmilalala | 来源:发表于2020-05-16 01:42 被阅读0次
    1. Go的数组只能有固定的长度,传入变量作为数组长度时,只能创建为定义了size的切片
    length := 5
    array := [length]int  // error: non-constant array bound length
    array := make([]int, length)
    
    1. Go没有内置的比较整数大小的方法,需要自己实现
    func max(a int, b int) int {
        if a >= b { 
            return a
        } else {
            return b
        }
    }
    
    1. Go没有内置的判断array或map是否存在某一个元素的方法,需要通过判断普通的get的error实现
    // implement array/list contains
    func contains(array []int, val int) bool {
        contains := false
        for _, value := range array {
            if val == value {
                contains = true
                break
            }
        }
        return contains
    }
    
    // implement map containsKey
    func containsKey(myMap map[int]int, key int) bool {
        if _, ok := myMap[key]; ok {
            return true
        } else {
            return false
        }
    }
    
    1. Golang使用动态切片长度作为for loop上限
      如果写作
    searchSet = getKeySet()
    for i :=0; i < len(searchSet); i++ {
        searchSet = append(searchSet, generateRandomKey())
    }
    

    可能会出现i无法察觉上限,无限循环

    Generate random key for i = 208944
    Enter generate random key
    Generate random key for i = 208945
    Enter generate random key
    Generate random key for i = 208946
    Enter generate random key
    Generate random key for i = 208947
    

    应该写作

    searchSet = getKeySet()
    size := len(searchSet)
    for i :=0; i < size; i++ {
        searchSet = append(searchSet, generateRandomKey())
    }
    
    1. Golang channel如果不close,遍历会出deadlock error
    ans := make(chan string)
    for i := 0; i<5; i++ {
        ans <- "hello"
    }
    // fatal error: all goroutines are asleep - deadlock!
    // need to close it before for loop, or read out fixed numbers of items
    // close(ans)
    for n, ok := range ans {
        fmt.Println(n)
    }
    
    1. Golang I/O Sample
    package main
    
    import (
        "os"
        "fmt"
        "context"
        "bufio"
    )
    
    func read() {
        textfile := "input.txt"
        file, err := os.Open(textfile)
        if err != nil {
            fmt.Printf("Cannot open text file: %s, err: [%v]", textfile, err)
        }
        defer file.Close()
    
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            line := scanner.Text()
            write(line)
        }
    
        if err := scanner.Err(); err != nil {
            fmt.Printf("Cannot scanner text file: %s, err: [%v]", textfile, err)
        }
    }
    
    func write(line string) {
        textfile := "output.txt"
        if file, err := os.OpenFile(textfile,os.O_RDWR|os.O_CREATE|os.O_APPEND,0644); err == nil {
            defer file.Close()
            writer := bufio.NewWriterSize(file)
            content := "My name is " + line
            if _,err := writer.WriteString(content); err == nil {
                fmt.Println("Successful appending buffer and flush to file with bufio's Writer obj WriteString method",content)
            }
        }
    }
    

    OpenFile flags

    const (
            O_RDONLY int = syscall.O_RDONLY // 只读打开文件和os.Open()同义
            O_WRONLY int = syscall.O_WRONLY // 只写打开文件
            O_RDWR   int = syscall.O_RDWR   // 读写方式打开文件
            O_APPEND int = syscall.O_APPEND // 当写的时候使用追加模式到文件末尾
            O_CREATE int = syscall.O_CREAT  // 如果文件不存在,此案创建
            O_EXCL   int = syscall.O_EXCL   // 和O_CREATE一起使用, 只有当文件不存在时才创建
            O_SYNC   int = syscall.O_SYNC   // 以同步I/O方式打开文件,直接写入硬盘.
            O_TRUNC  int = syscall.O_TRUNC  // 如果可以的话,当打开文件时先清空文件
    )
    

    相关文章

      网友评论

          本文标题:Golang Tips

          本文链接:https://www.haomeiwen.com/subject/mkwkohtx.html