目录
Please enable Javascript to view the contents

Go 常用函数备忘

 ·  ☕ 1 分钟

重要

记录开发中常用的 Go 代码片段。

1. 字符串转 int64

1
2
3
4
5
6
7
var s string = "9223372036854775807"
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
    panic(err)
}
fmt.Printf("Hello, %v with type %s!\n", i, reflect.TypeOf(i))
// Hello, 9223372036854775807 with type int64!

2. 最小化 gormigrate

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import (
    "gopkg.in/gormigrate.v1"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

m := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{
    {
        ID: "201608301400",
        Migrate: func(tx *gorm.DB) error {
            return tx.AutoMigrate(&Person{}).Error
        },
        Rollback: func(tx *gorm.DB) error {
            return tx.DropTable("people").Error
        },
    },
})
err = m.Migrate()

3. 判断元素在 Slice 中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func Find(slice []string, val string) (int, bool) {
    for i, item := range slice {
        if item == val {
            return i, true
        }
    }
    return -1, false
}

items := []string{"A", "1", "B", "2", "C", "3"}
k, found := Find(items, "B")
// found=true, k=2
分享

Hex
作者
Hex
CloudNative Developer