2 ms·
> hostname := os.Hostname().OrElse("localhost") You could do the following: type maybeString struct { val string err error } func MaybeString
by majewsky 8y ago
> 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"
}