markphelps / optional

Optional is a library of optional Go types
https://godoc.org/github.com/markphelps/optional
MIT License
209 stars 19 forks source link

`Get` without error / `Unwrap` method useful ? #12

Open tp opened 4 years ago

tp commented 4 years ago

Hey,

thanks for this utility :)

Coming from other languages, I wondered that there was not Unwrap which would return the value (or else panic if not set).

My thinking was, that I wrote code like this:

if s.field.Present() {
  doSth(s.field.Unwrap())
}

And then it didn't make sense to me to check the presence again / call Get which could return an error but never would in this case.

Then it occurred to me that I could write:

if field, err := s.field.Get(); err == nil {
  doSth(field)
}

The fact that error would always be errors.New("value not present") and never anything "bad" made me think though if this isn't too complicated to understand for the next reader (who might wonder why we wouldn't log the error etc.)

So basically I have 2 questions:

markphelps commented 3 years ago

Sorry this has taken me so long to respond to, somehow I did not get notifications for this repo for awhile and I just forgot to check 😬

I think I see your point about:

there is no general way to "handle the error", as mostly I would assume having an optional value not set is totally expected when using this library.

However I dont want to break backwards compatability so this may require a 'new' method to return value, ok instead of value, err

Also, I just released v0.9.0 which adds MustGet which panics if there is no value, which sounds like what you suggested for Unwrap?