小编Ste*_*isk的帖子

有没有办法在Golang中每隔一段时间做一次重复的任务?

有没有办法在Go中执行重复的后台任务?我在考虑类似Timer.schedule(task, delay, period)Java 的东西.我知道我可以用goroutine做到这一点Time.sleep(),但是我想要一些容易停止的东西.

这是我得到的,但看起来很难看.有更干净/更好的方式吗?

func oneWay() {
    var f func()
    var t *time.Timer

    f = func () {
        fmt.Println("doing stuff")
        t = time.AfterFunc(time.Duration(5) * time.Second, f)
    }

    t = time.AfterFunc(time.Duration(5) * time.Second, f)

    defer t.Stop()

    //simulate doing stuff
    time.Sleep(time.Minute)
}
Run Code Online (Sandbox Code Playgroud)

go

140
推荐指数
5
解决办法
8万
查看次数

为什么if语句中的struct创建在Go中是非法的?

Go抱怨在if语句中实例化一个struct.为什么?是否有正确的语法,不涉及临时变量或新函数?

type Auth struct {
    Username    string
    Password    string
}

func main() {
    auth := Auth { Username : "abc", Password : "123" }

    if auth == Auth {Username: "abc", Password: "123"} {
        fmt.Println(auth)
    }
}
Run Code Online (Sandbox Code Playgroud)

错误(在if语句行上):语法错误:意外:,期待:=或=或逗号

这会产生相同的错误:

if auth2 := Auth {Username: "abc", Password: "123"}; auth == auth2 {
            fmt.Println(auth)
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作:

auth2 := Auth {Username: "abc", Password: "123"};
if  auth == auth2 {
        fmt.Println(auth)
}
Run Code Online (Sandbox Code Playgroud)

go

10
推荐指数
1
解决办法
233
查看次数

标签 统计

go ×2