相关疑难解决方法(0)

Go中没有来自goroutine的输出

虽然SayHello()按预期执行,但goroutine没有打印任何内容.

package main

import "fmt"

func SayHello() {
    for i := 0; i < 10 ; i++ {
        fmt.Print(i, " ")
    }
}

func main() {
    SayHello()
    go SayHello()
}
Run Code Online (Sandbox Code Playgroud)

concurrency go goroutine

18
推荐指数
2
解决办法
1660
查看次数

将参数传递给函数闭包

我试图理解在创建一个带有参数的匿名函数与使该函数充当闭包之间的Go的区别.这是一个区别的例子.

带参数:

func main() {
  done := make(chan bool, 1)
  go func(c chan bool) {
    time.Sleep(50 * time.Millisecond)
    c <- true
  }(done)
  <-done
}
Run Code Online (Sandbox Code Playgroud)

作为封闭:

func main() {
  done := make(chan bool, 1)
  go func() {
    time.Sleep(50 * time.Millisecond)
    done <- true
  }()
  <-done
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,第一种形式何时优于第二种形式?你有没有使用参数来做这种事情?我唯一能看到第一种形式有用的是func(x, y)从另一个函数返回a时.

closures go

15
推荐指数
2
解决办法
7953
查看次数

Golang:使用环路切片/贴图的范围注册多个路线

考虑我有一些字符串路径:

paths := []string{"/path0", "/path1", "/path2" /*... "/path-n"*/ }
// where n is the last path
Run Code Online (Sandbox Code Playgroud)

使用包net/http,我想使用for带有range子句的循环注册此路径的处理程序.这就是我这样做的方式:

for _, path := range paths {
    http.HandleFunc(path, handler)
}
// in this case every handler is print the path to the console or to the browser
Run Code Online (Sandbox Code Playgroud)

但我最终得到了相同的输出,这是切片的最后一个元素,所以当我去/path1,输出是/path-n.与其他元素的行为相同,始终打印/path-n.

但如果我用这个:

for _, path := range paths {
    http.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, path)
    })
}
Run Code Online (Sandbox Code Playgroud)

输出是正确的.

发生了什么事,我错过了什么吗?我需要for通过切片路径或地图给出的循环注册,所以我不能做第二个代码.

你能给我替代完成这项任务吗?

routing closures for-loop go slice

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

标签 统计

go ×3

closures ×2

concurrency ×1

for-loop ×1

goroutine ×1

routing ×1

slice ×1