Re:On the uses and misuses of panics in Go
by majewsky on Thursday August 09, 2018 @06:35PM
(#17729152)
> hostname := os.Hostname().OrElse("localhost")
You could do the following: type maybeString struct {
val string
err error
}
func MaybeString(val string, err error) maybeString {
return maybeString{val, err}
}
func (m maybeString) OrElse(defaultValue string) string {
//...as above...
}
Then you can do: hostname := MaybeString(os.Hostname()).OrElse("localhost")
Of course, this is not practical on a large scale since you don't have generic types and thus would need to `go generate` one instance of the above for each MaybeXXX type. At this point, you're probably better off just writing hostname, err := os.Hostname()
if err != nil {
hostname = "localhost"
}
Re:On the uses and misuses of panics in Go
by golangnews on Thursday August 09, 2018 @02:53PM
(#17727281)
This (optional types) is one thing I'd really like them to explore for go 2.
Re:On the uses and misuses of panics in Go
by qalmakka on Thursday August 09, 2018 @04:10PM
(#17728018)
Yes, a fix to the mess error handling in Go is is long overdue, and I find Rust and Haskell approach one of the most effective ones, clear to understand and not too verbose, and yet powerful and relatively free of the mess exceptions are in other languages. I sincerely hope the Go authors will give sum types a shot in future releases of the languages, because they are so comically powerful that implementing them just feels like the right thing to do.
In those cases, errors are even more like normal values because they're returned using generic types (Optional/Maybe, Result/Either), not using hacky multiple return stuff.
For example, in go you might have a function that returns (string, error), but you can't define a method on that type that was returned, so e.g. you can't have:
This would let you right such code as: On the other hand, in rust or haskell you'd return a generic sum type which is either an error or a value and which can be treated as an actually normal value.This leads to the languages I mentioned above having the ability to have much cleaner and more concise error handling than go.
The fact that go has multiple returns, not tuples or sum types, results in its errors being really awkward to use values, among their other flaws.