golang记录

2018-09-21  本文已影响0人  苏州运维开发

获取本地IP

package main

import (
    "fmt"
    "net"
)

func LocalIp() string {
    addrs, err := net.InterfaceAddrs()
    if err != nil {
        fmt.Println(err)
    }
    var ip string = "localhost"
    for _, address := range addrs {
        if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                ip = ipnet.IP.String()
            }
        }
    }
    return ip
}

func main()  {
    fmt.Println(LocalIp())
}

限制golang最大并发数

package main

import (
    "fmt"
    "time"
)

func main()  {
    var limit = make(chan int , 3)   //限制最大并发数

    for i:=1 ; i <= 30 ; i++ {
        go func() {
            limit <- 1
            work()
            <-limit
        }()
    }
    select {}
}

func work()  {
    fmt.Println("work....")
    time.Sleep(1 * time.Second)
}

golang最快响应
伪代码如下

package main

import (
    "time"
    "fmt"
)

func remoteWork1()  string{
    time.Sleep(time.Second * 5)   //模拟响应时间
    return "work1"
}

func remoteWork2()  string{
    time.Sleep(time.Second * 2)   //模拟响应时间
    return "work2"
}

func remoteWork3()  string{
    time.Sleep(time.Second * 3)    //模拟响应时间
    return "work3"
}

func main()  {
    ch := make(chan string  )
    go func() {
        ch <- remoteWork1()
    }()
    go func() {
        ch <- remoteWork2()
    }()
    go func() {
        ch <- remoteWork3()
    }()
    fmt.Println(<-ch)      //以空间换时间,某些特定场景试用

}

反射修改对象属性

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

type TestObj struct {
    name string
    thisp this
    field1 string
}

type this struct {
    age []int
    address string
}


func main() {

    struct_ := &TestObj{name:"golang"}
    field, _ := reflect.TypeOf(struct_).Elem().FieldByName("thisp")
    field1Ptr := uintptr(unsafe.Pointer(struct_)) + field.Offset
    *((*this)(unsafe.Pointer(field1Ptr))) = this{[]int{1,2,3} ,"suzhou"}
    fmt.Println(struct_)
}

关于defer中坑的最佳解释
偶然在网上找到一份电子书《深入解析Go内核实现》(感谢作者)中有段关于解释defer执行原理的论述,真是言简意赅!
关键点:return xxx 不是一条原子指令!
defer坑如下:

package main

import "fmt"

func main()  {
    fmt.Println(f1())
    fmt.Println(f2())
    fmt.Println(f3())
    
}

func f1() (result int)  {
    defer func() {
        result++
    }()
    return 0
}

func f2() (r int)  {
    t := 5
    defer func() {
        t = t + 5
    }()
    return t
}

func f3() (r int)  {

    defer func(r int) {
        r = r + 5
    }(r)
    return 1
}

输出结果一次为:1,5,1
上述代码与下面的代码执行过程一致

package main

import (
    "fmt"
)

func main()  {
    fmt.Println(ff1())
    fmt.Println(ff2())
    fmt.Println(ff3())

}

func ff1() (result int)  {
    result = 0
    func(){
        result++
    }()
    return
}

func ff2() (r int)  {
    t := 5 
    r = t
    func(){
        t = t + 5   
    }()
    return
}

func ff3() (r int)  {
    r = 1
    func (n int) {
        n = n + 5
    }(r)
    return
}

该电子书中还有更多价值,值得深入研究的地方,大家可以自行下载参阅!

自定义迭代器

package main

import "fmt"

type agg struct {
    contain []int
}

func (a *agg) getIter() IIterator {
    i := new(Iterator)
    i.aggs = a
    return i
}


type IIterator interface {
    hasNext() bool
    next() bool
    current() int
}


type Iterator struct {
    cursor int
    aggs *agg
}
func (i *Iterator) hasNext() bool {
    if i.cursor + 1 > len(i.aggs.contain) {
        return false
    }else {
        return true
    }
}

func  (i *Iterator) next() bool {
    if i.cursor < len(i.aggs.contain) {
        i.cursor++
        return true
    }
    return false
}


func  (i *Iterator) current() int {
    return i.aggs.contain[i.cursor]
}


func main()  {
    a := new(agg)
    a.contain = []int{1,2,3,4,5,66}
    i := a.getIter()
    for {
        if i.hasNext() {
            fmt.Println(i.current())
            i.next()
        } else {
            break
        }
    }

}
上一篇 下一篇

猜你喜欢

热点阅读