Golang http.ResponseWriter报错:混合命名与未命名参数问题求助
解决Go中“mixed named and unnamed parameters”报错
你的代码报错核心原因是函数参数声明混合了命名与未命名格式。Go语言规定,函数的参数列表里,要么所有参数都同时指定名称和类型,要么只写类型(这种场景仅限接口方法定义等特定情况),不能一部分参数有名称、一部分只有类型。
看你写的helloWorldPage函数:
func helloWorldPage(w http.ResponseWriter, *http.Request) { fmt.Fprint(w, "hello world") }
第一个参数w有名称和类型,第二个参数却只有*http.Request类型没有参数名,这就触发了语法报错。
修正后的代码
给第二个参数补充一个名称(比如r,即便你暂时用不到这个参数,语法上也必须声明):
package main import ( "fmt" "net/http" ) func helloWorldPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello world") } func main() { http.HandleFunc("/", helloWorldPage) http.ListenAndServe(":8000", nil) }
修改后语法符合Go规范,运行代码后访问http://localhost:8000,就能在浏览器看到“hello world”了。
内容的提问来源于stack exchange,提问作者user21251189
相关产品推荐
相关产品推荐

