Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Struct properties with json.Unmarshal(): Why does the first letter have to be capitalized?

Following Situation:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    type person struct {
        Fullname string `json: "fullname"`
        Age      int    `json: "age"`
    }

    p := person{}

    err := json.Unmarshal([]byte(`{"fullname": "Michael Jackson", "age": 55}`), &p)

    fmt.Println(err) // <nil>
    fmt.Println(p)   // {Michael Jackson 55}
}

Why do I have to write Fullname (instead of, e.g. fullname)? Why does the first letter have to be capitalized? Which rule is that? Can I override this rule?

(because of copy+paste capability from another programming language, I don’t want to correct the first letter everywhere in copy-pasted structs.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: Go Playground

>Solution :

Go doesn’t have any public, private, or protected keyword. The only mechanism to control the visibility outside the package is using the capitalized and non-capitalized formats

Capitalized Identifiers are exported. The capital letter indicates that this is an exported identifier and is available outside the package.
Non-capitalized identifiers are not exported. The lowercase indicates that the identifier is not exported and will only be accessed from within the same package.
So any struct which starts with a capital letter is exported to other packages. Similarly, any struct field which starts with capital is exported otherwise not. And also similarly any struct method which starts with a capital letter is exported

For example:

type Account struct {
UserID      int    // exported
accessToken string // unexported

}

see more https://go.dev/tour/basics/3

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading