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\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

posted on   黑暗伯爵  阅读(1348)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2011-09-29 android 屏蔽指定activity启动(程序锁)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示