美文网首页golang
Go 语言程序设计(4)

Go 语言程序设计(4)

作者: hlemon | 来源:发表于2019-03-31 18:56 被阅读55次

    americanise.go 示例代码:

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "io/ioutil"
        "log"
        "os"
        "path/filepath"
        "regexp"
        "strings"
    )
    
    var britishAmerican = "./british-american.txt"
    
    func main() {
        inFilename, outFilename, err := filenameFromCommandLine()
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        inFile, outFile := os.Stdin, os.Stdout
        if inFilename != "" {
            if inFile, err = os.Open(inFilename); err != nil {
                log.Fatal(err)
            }
            defer inFile.Close()
        }
        if outFilename != "" {
            if outFile, err = os.Create(outFilename); err != nil {
                log.Fatal(err)
            }
            defer outFile.Close()
        }
        if err = americanise(inFile, outFile); err != nil {
            log.Fatal(err)
        }
    }
    
    func filenameFromCommandLine() (inFilename, outFilename string, err error) {
        if len(os.Args) > 1 && (os.Args[1] == "-h" || os.Args[1] == "--help") {
            err = fmt.Errorf("usage: %s [<]infile.txt [>]outfile.txt", filepath.Base(os.Args[0]))
            return "", "", err
        }
        if len(os.Args) >1 {
            inFilename = os.Args[1]
            if len(os.Args) > 2 {
                outFilename = os.Args[2]
            }
        }
        if inFilename != "" && inFilename == outFilename {
            log.Fatal("won't overwrite the infile")
        }
        return inFilename, outFilename, nil
    }
    
    func americanise(inFile io.Reader, outFile io.Writer) (err error)  {
        reader := bufio.NewReader(inFile)
        writer := bufio.NewWriter(outFile)
        defer func() {
            if err == nil {
                err = writer.Flush()
            }
        }()
        var replacer func(string) string
        britishAmericanPath, _ := filepath.Abs(britishAmerican)
        if replacer, err = makeReplacerFunc(britishAmericanPath); err != nil {
            return err
        }
        wordRx := regexp.MustCompile("[A-Za-z]+")
        eof := false
        for !eof {
            var line string
            line, err = reader.ReadString('\n')
            if err == io.EOF {
                err = nil
                eof = true
            } else if err != nil {
                return err
            }
            line = wordRx.ReplaceAllStringFunc(line, replacer)
            if _, err = writer.WriteString(line); err != nil {
                return err
            }
        }
        return nil
    }
    
    func makeReplacerFunc(file string) (func(string) string, error) {
        rawBytes, err := ioutil.ReadFile(file)
        if err != nil {
            return nil, err
        }
        text := string(rawBytes)
    
        usForBritish := make(map[string] string)
        lines := strings.Split(text, "\n")
        for _, line := range lines {
            fields := strings.Fields(line)
            if len(fields) == 2 {
                usForBritish[fields[0]] = fields[1]
            }
        }
    
        return func(word string) string {
            if usWord, found := usForBritish[word]; found {
                return usWord
            }
            return word
        }, nil
    }
    

    知识点:

    • bufio 包实现了有缓冲的I/O。它包装一个io.Reader或io.Writer接口对象,创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象
    • io 包提供了底层的 I/O 功能
    • io/ioutil 包实现了一些 I/O 实用函数
    • regexp 包实现了正则表达式搜索,和 PerlPython 等语言的正则基本一致
    • 性能对比 bufio > ioutill > os,对于不同的项目,选择不同的方法
    • panic 是一个运行时错误,我们可以通过内置的 panic() 函数触发一个异常,还能使用 recover() 函数阻止错误的传递
    • golang 定义 Map 的方法:
    /* 声明变量,默认 map 是 nil */
    var map_variable map[key_data_type]value_data_type
    
    /* 使用 make 函数 */
    map_variable := make(map[key_data_type]value_data_type)
    
    • 函数可以作为其它函数的参数进行传递,然后在其它函数内调用执行,一般称之为回调

    defer 用法:

    通过使用 defer 修饰一个函数,使其在外部函数 "返回后" 才被执行,即便外部的函数返回的是 panic 异常,这类函数被称作 延迟调用函数
    注意点:

    • defer 被声明时,其参数就会被实时解析
    • defer 执行顺序为先进后出
    • defer 可以读取有名返回值

    常见使用场景:

    • 简化资源的回收
    • panic 异常的捕获
    • 修改返回值
    • 安全的回收资源

    相关文档:

    相关文章

      网友评论

        本文标题:Go 语言程序设计(4)

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