douluokuang7184 2017-05-01 08:59
浏览 536
已采纳

Golang在Struct属性中的首字母使用小写

I have an issue with Golang view template, I currently using lowercase in the struct properties to build the struct then passed it to the view as a map.

here is my Struct look like:

type User struct {
      uid                  int
      username, departname string
}

then I passed the collection of structs to the file view:

func (App *App) indexHander(w http.ResponseWriter, r *http.Request) {
      rows, err := App.db.Query("SELECT * FROM userinfo")
      checkErr(err)

      t, _ := template.ParseFiles(App.folderpath + "/list.gtpl")

      users := make([]User, 0) // define empty collection of users

      for rows.Next() {
          var uid int 
          var username string
          var departname string
          var created string
          err = rows.Scan(&uid, &username, &departname, &created)
          checkErr(err)
          users = append(users, User{uid, username, departname})

      }   

      t.Execute(w, users)

      defer rows.Close()
  }

and here is my view html code:

<html>
      <head>
      <title></title>
      </head>
      <body>
          <ul>
          {{ range  . }}
             <li>{{ .username }}</li>
          {{ end }}
          </ul>
      </body>
  </html>

Those code above gave me empty users data: enter image description here

But however, using capitalize first letter in struct give me working result:

Struct

type User struct {
     Uid                  int
     Username, Departname string  
}

html

<html>
      <head>
      <title></title>
      </head>
      <body>
          <ul>
          {{ range  . }}
             <li>{{ .Username }}</li>
          {{ end }}
          </ul>
      </body>
  </html>

it works now

enter image description here

Can somebody explain me this behavior ?

  • 写回答

1条回答 默认 最新

  • du13932014807 2017-05-01 09:17
    关注

    read the doc here

    An identifier may be exported to permit access to it from another package. An identifier is exported if both:

    • the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu");
    • and the identifier is declared in thepackage block or it is a field name or method name.

    All other identifiers are not exported.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置