Go 若干技巧

本文介绍了Go语言中fmt包的使用技巧,包括格式化输出、结构体的打印方法及错误处理的最佳实践。同时,文章对比了不同异常处理方式,并强调了函数返回值一致性的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此文来自 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\n", foo) fmt.Printf("%T\n", 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\n\n", order) // 当我需要知道这个变量的有关结构时我会用这种方法 fmt.Printf("%#v\n\n", order) // 我很少使用这些 fmt.Printf("%v\n\n", order) fmt.Printf("%s\n\n", order) fmt.Printf("%T\n", 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\n", 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\n", 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

转载于:https://www.cnblogs.com/hangxin1940/p/3345504.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值