Go 若干技巧

Go 若干技巧

此文来自 http://denvergophers.com/2013-09/tips-and-tricks.slide

本文主要涉及到:

  1. formatting 技巧
  2. 异常处理技巧
  3. 函数返回值的一致性

代码资源:

https://denvergophers.com/tips-and-tricks

http://golang.org/pkg/fmt

http://godoc.org/code.google.com/p/go.tools/present

fmt包

使用如下格式导入:

import "fmt"

普通占位符:

%v  相应值的默认格式
%+v 在打印结构体时,会添加字段名
%#v 相应值的Go语法表示
%T  相应值的类型的Go语法表示
%%  字面上的百分号,并非值的占位符

fmt一般用法 - 简单字符串

var foo string = "This is a simple string"
fmt.Printf("%v
", foo)
fmt.Printf("%T
", foo)

fmt一般用法 - 结构(struct)

首先,准备好结构

type (
    Customer struct {
    Name   string
    Street []string
    City   string
    State  string
    Zip    string
    }
    Item struct {
    Id       int
    Name     string
    Quantity int
    }
    Items []Item
    Order struct {
    Id       int
    Customer Customer
    Items    Items
    }
)

关于结构格式化的一些技巧:

// 这是我调试时的默认格式
fmt.Printf("%+v

", order)

// 当我需要知道这个变量的有关结构时我会用这种方法
fmt.Printf("%#v

", order)

// 我很少使用这些
fmt.Printf("%v

", order)
fmt.Printf("%s

", order)
fmt.Printf("%T
", order)

fmt - 使用errors.New()生成Errors

这是我最不喜欢看到的创建异常的方式:

import (
    "errors"
    "fmt"
    "log"
)

func main() {
    if err := iDunBlowedUp(-100); err != nil {
        err = errors.New(fmt.Sprintf("Something went wrong: %s
", err))
        log.Println(err)
        return
    }
    fmt.Printf("Success!")
}

func iDunBlowedUp(val int) error {
    return errors.New(fmt.Sprintf("invalid value %d", val))
}

我是这么创建异常的:

import (
    "fmt"
    "log"
)

func main() {
    if err := iDunBlowedUp(-100); err != nil {
        err = fmt.Errorf("Something went wrong: %s
", err)
        log.Println(err)
        return
    }
    fmt.Printf("Success!")
}

func iDunBlowedUp(val int) error {
    return fmt.Errorf("invalid value %d", val)
}

fmt - 函数返回值的一致性

坏习惯:

func someFunction(val int) (ok bool, err error) {
    if val == 0 {
        return false, nil
    }
    if val < 0 {
        return false, fmt.Errorf("value can't be negative %d", val)
    }
    ok = true
    return
}

好习惯:

func someFunction(val int) (bool, error) {
    if val == 0 {
        return false, nil
    }
    if val < 0 {
        return false, fmt.Errorf("value can't be negative %d", val)
    }
    return true, nil
}

更好的方式(在我看来):

func someFunction(val int) (ok bool, err error) {
    if val == 0 {
        return
    }
    if val < 0 {
        err = fmt.Errorf("value can't be negative %d", val)
        return
    }
    ok = true
    return
}

参考

http://golang.org/

https://denvergophers.com/tips-and-tricks

http://golang.org/pkg/fmt

http://godoc.org/code.google.com/p/go.tools/present

作者相关

https://github.com/DenverGophers

https://twitter.com/DenverGophers

https://plus.google.com/u/0/communities/104822260820066412402

 
 
分类: Go
原文地址:https://www.cnblogs.com/Leo_wl/p/3345676.html