英文:
Bugs when running the example of go-libp2p-http
问题
问题出在go func中。错误信息是go中的表达式必须是函数调用。
listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
defer listener.Close()
go func() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi!"))
})
server := &http.Server{}
server.Serve(listener)
}
错误信息为
command-line-arguments
.\sever.go:18:5: expression in go must be function call
英文:
The problem lies in go func. The error message is expression in go must be function call
listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
defer listener.Close()
go func() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi!"))
})
server := &http.Server{}
server.Serve(listener)
}
The error is
command-line-arguments
.\sever.go:18:5: expression in go must be function call
答案1
得分: 0
你忘记调用(调用)匿名函数了。因此,出现错误:go中的表达式必须是函数调用。
go func() { fmt.Prinln("我是一个IIFE") }() // 注意括号
这被称为立即调用的函数表达式(IIFE)。
英文:
You forget to invoke (call) the anonymous function. Hence, the error: expression in go must be function call.
go func() { fmt.Prinln("Im an IIFE") }() // note the parenthesis
This is called immediate invoked function expression (IIFE).
答案2
得分: 0
如果你决定创建一个匿名函数,那么可以使用以下代码:
listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
defer listener.Close()
go func() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi!"))
})
server := &http.Server{}
server.Serve(listener)
}()
如果你想使用命名函数,可以使用以下代码:
listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
defer listener.Close()
go Greet()
func Greet() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi!"))
})
server := &http.Server{}
server.Serve(listener)
}
英文:
If you decide to make an anonymous function, then
listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
defer listener.Close()
go func() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi!"))
})
server := &http.Server{}
server.Serve(listener)
}()
Named function:
listener, _ := gostream.Listen(host1, p2phttp.DefaultP2PProtocol)
defer listener.Close()
go Greet()
func Greet() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hi!"))
})
server := &http.Server{}
server.Serve(listener)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论