Go语言学习 Day05 Summary part2

1. Defer

Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages.

Suppose we wanted to create a file, write to it, and then close when we’re done. Here’s how we could do that with defer.

Immediately after getting a file object with createFile, we defer the closing of that file with closeFile. This will be executed at the end of the enclosing function (main), after writeFile has finished.

It’s important to check for errors when closing a file, even in a deferred function.

[maxwell@oracle-db-19c Day05]$ vim defer.go    
[maxwell@oracle-db-19c Day05]$ cat defer.go    
package main

import (
     "fmt"
     "os"
)

func main(){

     f := createFile("/tmp/defer.txt")
     defer closeFile(f)
     writeFile(f)
}

func createFile(p string) *os.File {
    fmt.Println("creating")
    f,err := os.Create(p)
    if err != nil{
        panic(err)
    }
    return f
}

func writeFile(f *os.File){
    fmt.Println("writing")
    fmt.Println(f, "data")
}

func closeFile(f *os.File){
    fmt.Println("closing")
    err := f.Close()

    if err != nil {
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(1)
    }

}
[maxwell@oracle-db-19c Day05]$ go run defer.go 
creating
writing
&{0xc0000b0120} data
closing
[maxwell@oracle-db-19c Day05]$ 

2. Recover

Go makes it possible to recover from a panic, by using the recover built-in function. A recover can stop a panic from aborting the program and let it continue with execution instead.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients. In fact, this is what Go’s net/http does by default for HTTP servers.

[maxwell@oracle-db-19c Day05]$ vim recover.go
[maxwell@oracle-db-19c Day05]$ cat recover.go
package main

import "fmt"

func mayPanic() {
    panic("a problem")
}

func main(){

     defer func(){
        if r := recover(); r != nil {

           fmt.Println("Recovered. Error:\n",r)
        }
     }()

     mayPanic()

     fmt.Println("After mayPanic()")
}
[maxwell@oracle-db-19c Day05]$ go run recover.go
Recovered. Error:
 a problem
[maxwell@oracle-db-19c Day05]$ 

3.String Functions

The standard library’s strings package provides many useful string-related functions. Here are some examples to give you a sense of the package.

Here’s a sample of the functions available in strings. Since these are functions from the package, not methods on the string object itself, we need pass the string in question as the first argument to the function. You can find more functions in the strings package docs.

[maxwell@oracle-db-19c Day05]$ vim string_functions.go    
[maxwell@oracle-db-19c Day05]$ cat string_functions.go    
package main

import (
    "fmt"
    s "strings"
)

var p = fmt.Println

func main(){
    p("Contains: ", s.Contains("test", "es"))
    p("Count: ", s.Count("test", "t"))
    p("HashPrefix: ", s.HasPrefix("test", "te"))
    p("HasSuffix: ", s.HasSuffix("test", "st"))
    p("Index: ", s.Index("test", "e"))
    p("Join: ", s.Join([]string{"a","b"}, "-"))
    p("Repeat: ", s.Repeat("a", 5))
    p("Replace: ", s.Replace("foo", "o","0",-1))
    p("Replace: ", s.Replace("foo", "o","0",1))
    p("Split: ", s.Split("a-b-c-d-e", "-"))
    p("ToLower: ", s.ToLower("TEST"))
    p("ToUpper: ", s.ToUpper("test"))
}
[maxwell@oracle-db-19c Day05]$ go run string_functions.go 
Contains:  true
Count:  2
HashPrefix:  true
HasSuffix:  true
Index:  1
Join:  a-b
Repeat:  aaaaa
Replace:  f00
Replace:  f0o
Split:  [a b c d e]
ToLower:  test
ToUpper:  TEST
[maxwell@oracle-db-19c Day05]$ 

4.String Formatting

Go offers excellent support for string formatting in the printf tradition. Here are some examples of common string formatting tasks.

[maxwell@oracle-db-19c Day05]$ vim string_formatting.go
[maxwell@oracle-db-19c Day05]$ cat string_formatting.go
package main

import (
     "fmt"
     "os"
)


type point struct {
    x, y int
}


func main(){
    p := point{1, 2}
    fmt.Printf("struct1: %v\n", p)

    fmt.Printf("struct2: %+v\n", p)

    fmt.Printf("Struct3: %#v\n", p)


    fmt.Printf("type: %T\n", p)
    fmt.Printf("bool: %t\n", true)
    fmt.Printf("int: %d\n", 123)

    fmt.Printf("bin: %b\n", 14)
    fmt.Printf("char: %c\n", 33)

    fmt.Printf("hex: %x\n", 456)
    fmt.Printf("float1: %f\n", 78.9)

    fmt.Printf("float2: %e\n", 123400000.0)
    fmt.Printf("float3: %E\n", 123400000.0)


    fmt.Printf("str1: %s\n", "\"string\"")
    fmt.Printf("str2: %q\n", "\"string\"")
    fmt.Printf("str3: %x\n", "hex this")

    fmt.Printf("pointer: %p\n", &p)

    fmt.Printf("width1: |%6d|%6d|\n", 12,345)

    fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2,3.45)

    fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2,3.45)

    fmt.Printf("width4: |%6s|%6s|\n", "foo","b")

    s := fmt.Sprintf("Sprintf: a %s", "string")
    fmt.Println(s)

    fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
}
[maxwell@oracle-db-19c Day05]$ go run string_formatting.go
struct1: {1 2}
struct2: {x:1 y:2}
Struct3: main.point{x:1, y:2}
type: main.point
bool: true
int: 123
bin: 1110
char: !
hex: 1c8
float1: 78.900000
float2: 1.234000e+08
float3: 1.234000E+08
str1: "string"
str2: "\"string\""
str3: 6865782074686973
pointer: 0xc00001a0a0
width1: |    12|   345|
width2: |  1.20|  3.45|
width3: |1.20  |3.45  |
width4: |   foo|     b|
Sprintf: a string
io: an error
[maxwell@oracle-db-19c Day05]$ 

5.Text Templates

Go offers built-in support for creating dynamic content or showing customized output to the user with the text/template package. A sibling package named html/template provides the same API but has additional security features and should be used for generating HTML.

[maxwell@oracle-db-19c Day05]$ vim text_templates.go   
[maxwell@oracle-db-19c Day05]$ cat text_templates.go   
package main

import (
     "os"
     "text/template"
)

func main(){
    t1 := template.New("t1")
    t1, err := t1.Parse("Value is {{.}}\n")
    if err != nil {
        panic(err)
    }

    t1 = template.Must(t1.Parse("Value: {{.}}\n"))

    t1.Execute(os.Stdout, "some text")
    t1.Execute(os.Stdout, 5)
    t1.Execute(os.Stdout, []string{
        "Go",
        "Rust",
        "C++",
        "C#",
    })

    Create := func(name, t string) * template.Template {
        return template.Must(template.New(name).Parse(t))
    }

    t2 := Create("t2","Name: {{.Name}}\n")


    t2.Execute(os.Stdout, struct{
        Name string
    }{"Jane Doe"})

    t2.Execute(os.Stdout,map[string]string{
        "Name": "Mickey Mouse",
    })

    t3 := Create("t3", "{{if . -}} yes {{else -}} no {{end}}\n")

    t3.Execute(os.Stdout, "not empty")
    t3.Execute(os.Stdout, "")

    t4 := Create("t4","Range: {{range .}}{{ . }}{{end}}\n")

    t4.Execute(os.Stdout,
        []string{
            "Go",
            "Rust",
            "C++",
            "C#",
        })
}
[maxwell@oracle-db-19c Day05]$ go run text_templates.go
Value: some text
Value: 5
Value: [Go Rust C++ C#]
Name: Jane Doe
Name: Mickey Mouse
yes 
no 
Range: GoRustC++C#
[maxwell@oracle-db-19c Day05]$ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值