Go

Go 单元测试

Submitted by Lizhe on Fri, 10/26/2018 - 13:57

 

 

package lizhe

 

import (

    "errors"

)

 

func Division(a, b float64) (float64, error) {

    if b == 0 {

        return 0, errors.New("除数不能为0")

    }

 

    return a / b, nil

}

 

 

package lizhe

Go 反射

Submitted by Lizhe on Fri, 10/26/2018 - 11:23

package main

 

import (

    "fmt"

    "reflect"

)

 

type User struct {

    Id int

    Name string

    Age int

}

 

func (u User) Hello() {

    fmt.Println("Hello world!")

}

func Info(o interface{}) {

    t := reflect.TypeOf(o)

    fmt.Println("Type:", t.Name())

 

Go 读写mysql

Submitted by Lizhe on Thu, 10/25/2018 - 18:00

package main

 

import (

    "database/sql"

    "log"

 

    _ "github.com/go-sql-driver/mysql"

)

 

func checkErr(err error) {

 

    if err != nil {

 

        //log.Println(err)

 

    }

 

}

 

func main() {

 

Go 多线程 (4)

Submitted by Lizhe on Tue, 10/23/2018 - 15:26

sync.Pool 用于缓存

1. pool 可以减少GC对高并发的性能影响
2. 提供了对象重用
3. 并发安全
4. 仅受限于内存大小
5. 减少GC
6. 对象被删除时不会通知
7. 动态扩容或者收缩

package main

 

import (

    "log"

    "sync"

)

 

func main() {

    var intPool = sync.Pool{}

    for i := 0; i < 5; i++ {

        intPool.Put(i)

    }

    log.Println(intPool.Get())

Go 多线程 (3)

Submitted by Lizhe on Tue, 10/23/2018 - 12:25

通道

atomic和互斥锁都可以保证线程安全, 不过在go语言里, 还有一种有趣的实现就是通道

package main

 

import (

    "fmt"

)

 

func main() {

    buffered := make(chan string, 10)

    buffered <- "hello world"

    value := <-buffered

    fmt.Println(value)

}

 

当一个资源需要在goroutine之间共享时, 通道在goroutine之间传递数据, 并且还提供了同步交换数据的机制.

Go 多线程 (2)

Submitted by Lizhe on Mon, 10/22/2018 - 12:23

 

线程不安全的版本

package main

 

import (

    "fmt"

    "runtime"

    "sync"

)

 

var (

    count int32

    wg sync.WaitGroup

)

 

func main() {

    wg.Add(2)

    go addValue()

    go addValue()

    wg.Wait()

    fmt.Println(count)

}

 

func addValue() {

    defer wg.Done()

Go 多线程 (1)

Submitted by Lizhe on Mon, 10/22/2018 - 11:43

 

下面的代码创建了两个匿名的异步函数, 然后通过waitgroup来等待这两个异步方法

package main

 

import (

    "fmt"

    "sync"

)

 

func main() {

    var wg sync.WaitGroup

    wg.Add(2)

    fmt.Println("Started...")

 

    go func() {

        defer wg.Done()

        fmt.Println("first thread finished")

    }()

 

    go func() {

Go 闭包

Submitted by Lizhe on Wed, 09/13/2017 - 10:59

package main

import (
    "fmt"
)

func main() {
    function := squares()
    fmt.Println(function())
    fmt.Println(function())
    fmt.Println(function())
    fmt.Println(function())
}

func squares() func() int {
    var x int
    return func() int {
        x++
        return x*x
    }
}