Skip to content

Instantly share code, notes, and snippets.

View tomtsang's full-sized avatar

tomtsang tomtsang

  • ttechnology
  • china
View GitHub Profile
@tomtsang
tomtsang / golang-factory-func.go
Created February 7, 2018 15:11
golang-factory-func.go
// 应用闭包:将函数作为返回值
// 工厂函数
func MakeAddSuffix(suffix string) func(string) string {
return func(name string) string {
if !strings.HasSuffix(name, suffix) {
return name + suffix
}
return name
}
@tomtsang
tomtsang / golang-where.go
Created February 7, 2018 15:10
golang-where.go
// 在需要的时候实现一个 where() 闭包函数来打印函数执行的位置:
where := func() {
_, file, line, _ := runtime.Caller(1)
log.Printf("%s:%d", file, line)
}
where()
// some code
where()
// some more code
@tomtsang
tomtsang / fibonacci.go
Created February 7, 2018 14:31
fibonacci.go
package main
import "fmt"
func main() {
result := 0
for i := 0; i <= 10; i++ {
result = fibonacci(i)
fmt.Printf("fibonacci(%d) is: %d\n", i, result)
}
@tomtsang
tomtsang / golang-func-defer-log-values.go
Created February 7, 2018 14:18
golang-func-defer-log-values.go
//下面的代码展示了另一种在调试时使用 defer 语句的手法(示例 6.12 defer_logvalues.go):
package main
import (
"io"
"log"
)
func func1(s string) (n int, err error) {
@tomtsang
tomtsang / golang-func-defer-2
Created February 7, 2018 13:29
golang-func-defer-2
package main
import "fmt"
func trace(s string) string {
fmt.Println("entering:", s)
return s
}
func un(s string) {
@tomtsang
tomtsang / golang-func-defer
Created February 7, 2018 13:28
golang-func-defer
package main
import "fmt"
func main() {
doDBOperations()
}
func connectToDB() {
fmt.Println("ok, connected to db")
@tomtsang
tomtsang / golang-func-6.3
Created February 7, 2018 13:25
golang-func-6.3
//6.3 传递变长参数
func typecheck(..,..,values … interface{}) {
for _, value := range values {
switch v := value.(type) {
case int: …
case float: …
case string: …
case bool: …
default: …
}
@tomtsang
tomtsang / golang-for-pattern2
Created February 7, 2018 08:52
golang-for-pattern2
for ix, val := range coll { }
@tomtsang
tomtsang / golang-for-pattern1
Created February 7, 2018 07:11
golang-for-pattern1
// for 初始化语句; 条件语句; 修饰语句 {}
for i := 0; i < 5; i++ {
fmt.Printf("This is the %d iteration\n", i)
}
/*
初始化语句
for 条件语句 {
修饰语句
@tomtsang
tomtsang / golang-switch-fallthrough
Created February 7, 2018 06:40
golang-switch-fallthrough
switch i {
case 0: // 空分支,只有当 i == 0 时才会进入分支
case 1:
f() // 当 i == 0 时函数不会被调用
}
switch i {
case 0: fallthrough
case 1:
f() // 当 i == 0 时函数也会被调用