这可能不是最优雅的解决方案,但却是我能找到的最好的解决方案:
http://play.golang.org/p/MT91mLqk1s
package mainimport ( "os" "reflect" "text/template")var fns = template.FuncMap{ "last": func(x int, a interface{}) bool { return x == reflect.ValueOf(a).Len() - 1 },}func main() { t := template.Must(template.New("abc").Funcs(fns).Parse(`{{range $i, $e := .}}{{if $i}}, {{end}}{{if last $i $}}and {{end}}{{$e}}{{end}}.`)) a := []string{"one", "two", "three"} t.Execute(os.Stdout, a)}注意: 您也可以使用以下
len功能(不计入Russ Cox
的功能)进行反射:http :
//play.golang.org/p/V94BPN0uKD
cf
- https://groups.google.com/forum/#!topic/golang-nuts/yRXHSCjVAcM
- https://groups.google.com/forum/#!msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ
- https://groups.google.com/forum/#!topic/golang-nuts/mqRbR7AFJj0



