Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yisiper opened this issue Mar 28, 2015 · 2 comments
Closed

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

yisiper opened this issue Mar 28, 2015 · 2 comments

Comments

@yisiper
Copy link

yisiper commented Mar 28, 2015

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)

@rsc
Copy link
Contributor

rsc commented Apr 9, 2015

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
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants