I am interested in error-related changes. Frequently I want to check for an
error, and pass it 'up' if it occurs:
_, err := someFn()
if nil!=err { return err }
I've tidied that up a little to
if _,err :=someFn(); nil!=err {
return err
}
This almost becomes boilerplate, and causes a lot of tedious repetition and
duplication. If I change my function return signature, I have to duplicate
this at each point.
I would like to have something like this:
func inFix(err error) (string,error) {
return "", err
}
func GenerateError() (string,error) {
return "", errors.New("My error")
}
func One() (string,error) {
x, ^inFix := GenerateError()
return x, nil
}
The rules are simple:
r1. A 'hat' function can take only a single parameter, an interface{} or a
pointer - anything that can be nil, and MUST return the same values as the
function in which it is called.
r2. It is a compilation error to ^ a hat function within a containing
function that has a different return signature.
In my example, it would be a compilation error to use ^ inFix function
in a function returning (int, error)
r3. If a ^ appears in an assignment position, it must be in the position of
an interface return value that matches the parameter of the hat function.
In my example, ^inFix occurs at the position where 'error' is being
returned. Since inFix takes an error parameter, this matches. Anything else
would be a compilation error.
r4. If the parameter returned by the function in the position of the ^ call
is not-nil, the hat function is called, and the return values of the hat
function are returned by the containing function.
Implementation notes:
i1. A crude compilation:
x, ^h := f(x)
expands to:
var err_h error
// define x if it's not already defined
if x,err_h = f(x); nil!=err_h {
return h(err_h)
}
Observations:
o1. The ^ in the syntax is not obviously necessary. However, it does
prevent ambiguity in the case of := where the first variable is not defined:
x, inFix := GenerateError()
This clearly means define 'x', but does it mean define a local variable
inFix of type error, or use the global inFix(error) function as a hat
function? ^ removes the ambiguity.
o2. I've not thought of a way to make this even more generic. At this level
of definition, a hat function can take only one nil-able parameter. Might
one think of something more flexible?
Finally:
I'd be very interested if more experienced Gopher's tell me I'm doing
errors all wrong, or that I'm messing up if I'm just passing errors 'up'
the stack. Please don't hesitate to criticize.
All the best,
Craig
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.