英文:
Go syntax error, unbalanced braces
问题
当我尝试运行我的应用程序时,它显示在第32行有一个意外的}
。我已经数了一下{
和}
,似乎它们是匹配的,但是当我移除f1、f2和p时,它就可以正常工作了。我该如何修复这个问题?
package main
import (
"fmt"
"log"
"net/http"
"html/template"
)
type friend struct{
fname string
}
type person struct{
username string
emails []string
friends []*friend
}
func home(w http.ResponseWriter, r *http.Request){
f1 := friend{fname: "minux.ma"}
f2 := friend{fname: "xushiwei"}
p := Person{
userName: "Astaxie",
emails: []string{"astaxie@beego.me", "astaxie@gmail.com"},
friends: []*Friend{&f1, &f2},
}
t, err := template.ParseFiles("template.gtpl")
if err != nil{
fmt.Println(err)
}
t.Execute(w, nil)
}
func main(){
http.HandleFunc("/", home)
err := http.ListenAndServe(":8000", nil)
if err != nil{
log.Fatal("listen and serve:", err)
}
}
英文:
When I'm trying to run my app it says that there is an unexpected }
in line 32, I have counted {
and }
, seems they are even but when I remove f1, f2 and p it works well. How can I fix this?
package main
import (
"fmt"
"log"
"net/http"
"html/template"
)
type friend struct{
fname string
}
type person struct{
username string
emails []string
friends []*friend
}
func home(w http.ResponseWriter, r *http.Request){
f1 := friend{fname: "minux.ma"}
f2 := friend{fname: "xushiwei"}
p := Person{
userName: "Astaxie",
emails: []string{"astaxie@beego.me", "astaxie@gmail.com"},
friends: []*Friend{&f1, &f2}
}
t, err := template.ParseFiles("template.gtpl")
if err != nil{
fmt.Println(err)
}
t.Execute(w, nil)
}
func main(){
http.HandleFunc("/", home)
err := http.ListenAndServe(":8000", nil)
if err != nil{
log.Fatal("listen and serve:", err)
}
}
答案1
得分: 3
你的代码中有一个意外的}
,因为在friends
行的末尾缺少了逗号。
friends: []*Friend{&f1, &f2},
始终使用go fmt
格式化你的代码(或使用goimports
)。它会给出一个带有准确行和列的错误提示:
在复合字面量中换行之前缺少
,
。
英文:
There's an unexpected }
, because you're missing a comma on the end of the friends
line
friends: []*Friend{&f1, &f2},
Always go fmt
your code. (or use goimports
). It will give you an error with the exact line and column:
> missing ',' before newline in composite literal
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论