Go语法错误,括号不平衡。

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年1月23日 05:25:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/34956202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定