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

Advertisements

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.)

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

Leave a ReplyCancel reply