zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Win7下通过eclipse远程连接CDH集群来执行相应的程序以及错误说明
    Java中的Scanner类和String类
    java的eclipse操作和常用类Object的使用
    如何利用Cloudera Manager来手动安装parcel包
    java.io.IOException: Too many open files
    java中的包以及内部类的介绍
    HDFS中的checkpoint( 检查点 )的问题
    HDFS中Java的API使用测试
    利用ClouderaManager启动HBase时,出现 master.TableNamespaceManager: Namespace table not found. Creating...
    MapReducer程序调试技巧
  • 原文地址:https://www.cnblogs.com/hangxin1940/p/3345504.html
Copyright © 2011-2022 走看看