Skip to content

Struct field json:"xxx,omitempty" return nil when reference #173

Closed
@yisiper

Description

@yisiper

I am trying to get github user repositories
https://gist.github.com/yisiper/48ea8ddc9c48d97e7a9f

Not all repositories return it's language , the return json may just {language : null}, thus the pointer in struct point to nil.

it need to do many pointer nil checking before use those field.
Is it possible to let the default type initialized?
says string should be "", int should be 0.

ref: #19 (comment)

Activity

rsc

rsc commented on Apr 9, 2015

@rsc
Contributor

I use helpers like this in my own code using this package:

func getInt(x *int) int {
    if x == nil {
        return 0
    }
    return *x
}

func getString(x *string) string {
    if x == nil {
        return ""
    }
    return *x
}

func getUserLogin(x *github.User) string {
    if x == nil || x.Login == nil {
        return ""
    }
    return *x.Login
}

func getTime(x *time.Time) time.Time {
    if x == nil {
        return time.Time{}
    }
    return *x
}

func getMilestoneTitle(x *github.Milestone) string {
    if x == nil || x.Title == nil {
        return ""
    }
    return *x.Title
}

func getLabelNames(x []github.Label) []string {
    var out []string
    for _, lab := range x {
        out = append(out, getString(lab.Name))
    }
    sort.Strings(out)
    return out
}

Then if you don't care about present vs not present, you can use, say, getString(issue.Xxx) instead of checking whether issue.Xxx is nil.

willnorris

willnorris commented on Apr 28, 2015

@willnorris
Collaborator

Unfortunately, there's not an easy solution to this. #19 certainly does have all the discussion that led to this design, but I also wrote about it here if you're interested.

The best solution will be to implement #45, which is what the proto library does. go generate didn't exist when I originally filed that issue, so it would actually be much easier to implement now.

Closing this for now, as there isn't actually anything to do here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @willnorris@rsc@yisiper

        Issue actions

          Struct field `json:"xxx,omitempty"` return nil when reference · Issue #173 · google/go-github