Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang using lowercase for first letter in Struct property

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 ?

like image 899
Yusuf Ibrahim Avatar asked Mar 09 '23 05:03

Yusuf Ibrahim


1 Answers

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.

like image 83
Yoesoff Avatar answered Mar 23 '23 08:03

Yoesoff