Please enable Javascript to view the contents

Go-常用函数备忘

 ·  ☕ 1 分钟

重要

记录常用的一些函数

1. 字符串转int64

1
2
3
4
5
6
7
// Use the max value for signed 64 integer. http://golang.org/pkg/builtin/#int64
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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main

import (
    "log"

    "gopkg.in/gormigrate.v1"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Person struct {
    gorm.Model
    Name string
}

type Pet struct {
    gorm.Model
    Name     string
    PersonID int
}

func main() {
    db, err := gorm.Open("sqlite3", "mydb.sqlite3")
    if err != nil {
        log.Fatal(err)
    }
    if err = db.DB().Ping(); err != nil {
        log.Fatal(err)
    }

    db.LogMode(true)

    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
            },
        },
        {
            ID: "201608301430",
            Migrate: func(tx *gorm.DB) error {
                return tx.AutoMigrate(&Pet{}).Error
            },
            Rollback: func(tx *gorm.DB) error {
                return tx.DropTable("pets").Error
            },
        },
    })

    err = m.Migrate()
    if err == nil {
        log.Printf("Migration did run successfully")
    } else {
        log.Printf("Could not migrate: %v", err)
    }
}

3. 判断元素在Slice

 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
32
33
34
package main

import (
    "fmt"
)

func main() {

    items := []string{"A", "1", "B", "2", "C", "3"}

    // Missing Example
    _, found := Find(items, "golangcode.com")
    if !found {
        fmt.Println("Value not found in slice")
    }

    // Found example
    k, found := Find(items, "B")
    if !found {
        fmt.Println("Value not found in slice")
    }
    fmt.Printf("B found at key: %d\n", k)
}

// Find takes a slice and looks for an element in it. If found it will
// return it's key, otherwise it will return -1 and a bool of false.
func Find(slice []string, val string) (int, bool) {
    for i, item := range slice {
        if item == val {
            return i, true
        }
    }
    return -1, false
}

Reference

分享

Hex
作者
Hex
CloudNative Developer

目录