Skip to content
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

Expand Reset() method on *struct? #432

Closed
dotwaffle opened this issue Jul 19, 2018 · 4 comments
Closed

Expand Reset() method on *struct? #432

dotwaffle opened this issue Jul 19, 2018 · 4 comments
Labels

Comments

@dotwaffle
Copy link

Before I looked into this, I was wondering if the following was a common occurrence or not, but couldn't find too many people thinking the same way.

Let's say I have a generated type and instance of it:

type X struct{
    A *types.StringValue
    B *types.Int64Value
    C *types.Int32Value
}
myX := new(X)

I need to frequently dive into the godoc to find out what type B is, and then new(types.Int64Value) and then set Value (or &types.Int64Value{Value: 0}) which can be quite verbose and ugly.

I figured that if Reset() wipes out a struct's values, and setting the pointer to nil removes the struct, there's surely scope for creating something the other way around -- going from nil (unset because you just ran new() on the parent) to an initialized struct without having to go to great lengths of boilerplate?

At the moment, if you run Reset() on a nil pointer, you get a nil pointer dereference panic. It would be good to test for nil first and new(type) it or something similar.

The closest thing I can see to making this better is upstream at golang/protobuf#414 but that doesn't seem to have gained much traction and still doesn't properly solve the nil pointer issue.

Thoughts / observations?

@dotwaffle
Copy link
Author

Although thinking about it, the Reset() method passes in the pointer, which is nil, which you can't rewrite. I can't think of an elegant solution to that problem...

@awalterschulze
Copy link
Member

Sorry for the delay.
Someone recently reported an issue with the SetDefaults function, which I didn't know existed.
Does this sound like something you are looking for.
Maybe you could copy it and adjust it for your use case?

@awalterschulze
Copy link
Member

func SetDefaults(pb Message) {

@dotwaffle
Copy link
Author

This ended up being far more complicated to implement in a friendly way for the consumers of the library I am writing than I ideally like, it's just easier to do new(type) or &type{}.

Thank you for the pointer though (forgive the pun!) -- this taught me something new at least!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants