I am trying to have this print out something like [{coolGuy} {penguin}]
but for some reason it just prints out [{} {}]
. What is the problem?
package main
import (
"fmt"
"encoding/json"
)
type Username struct {
username string
}
func main() {
usernamesJson := `[{"username":"coolGuy"},{"username":"penguin"}]`;
var usernames []Username;
err := json.Unmarshal([]byte(usernamesJson), &usernames);
if err != nil {
fmt.Println(err);
}
fmt.Printf("%v\n", usernames);
}
CodePudding user response:
Field username
is not exported. To export a field it needs to start with an uppercase letter:
type Username struct {
Username string
}
Because Unmarshal()
lives in different package (json
) it does not have access to unexported fields in your struct. If you want to make any field visible to out of your package code it needs to be exported. In Go marking field, type, variable, function exported is simply done by starting its name with an uppercase letter.