Golang中为什么结构体的'title'字段是未导出的?

Golang中为什么结构体的’title’字段是未导出的? 我遇到这个错误:

template: header.gohtml:6:13: executing “header” at <.title>: title is an unexported field of struct type main.pageData

main.go

type pageData struct {
	title string
	firstname string
}

func apply(w http.ResponseWriter, r *http.Request) {
	pd := pageData{title: "Apply"}
	var firstname string
	if r.Method == http.MethodPost {
		firstname = r.FormValue("firstname")
		pd.firstname = firstname
	}
}

templates/apply.gohtml

{{template "header" .}}
<h1>APPLY</h1>
{{if .title}}
Your name is {{.title}}
{{end}}
{{template "nav-main"}}
{{template "footer"}}

templates/includes/header.gohtml

{{ define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.title}}</title>
    <link rel="stylesheet" href="/public">
</head>
<body>
{{end}}

我的代码有什么问题?


更多关于Golang中为什么结构体的'title'字段是未导出的?的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

很高兴知道这一点。非常感谢!

更多关于Golang中为什么结构体的'title'字段是未导出的?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


“export” 表示"公开" => 使用首字母大写 原因很简单:渲染器包使用 reflect 包来获取/设置字段值 reflect 包只能访问公共/导出的结构体字段。 所以请尝试定义:

type pageData struct {
	Title string
	Firstname string
}

在Go语言中,结构体字段的可见性由字段名的首字母大小写决定。只有首字母大写的字段才是导出的(公开的),可以在包外部访问。在你的代码中,title字段是小写的,因此是未导出的,无法在模板中访问。

错误信息明确指出titlemain.pageData结构体的未导出字段。当模板引擎尝试访问.title时,由于字段未导出,导致访问失败。

解决方案:

pageData结构体的字段名首字母大写,使其成为导出字段:

type pageData struct {
    Title     string
    Firstname string
}

func apply(w http.ResponseWriter, r *http.Request) {
    pd := pageData{Title: "Apply"} // 注意字段名改为大写
    var firstname string
    if r.Method == http.MethodPost {
        firstname = r.FormValue("firstname")
        pd.Firstname = firstname // 字段名改为大写
    }
}

同时,在模板中也需要使用大写的字段名:

templates/apply.gohtml

{{template "header" .}}
<h1>APPLY</h1>
{{if .Title}} <!-- 改为 .Title -->
Your name is {{.Title}} <!-- 改为 .Title -->
{{end}}
{{template "nav-main"}}
{{template "footer"}}

templates/includes/header.gohtml

{{ define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.Title}}</title> <!-- 改为 .Title -->
    <link rel="stylesheet" href="/public">
</head>
<body>
{{end}}

这个修改确保了pageData结构体的字段在模板引擎中是可访问的,因为Go的模板引擎通过反射来访问结构体的导出字段。

回到顶部