3 ms·
> If you have "func bar() (MyStruct, error)", you cannot do "foo(bar())". You must always assign the result to an intermediate variable. You could embed the err
by vruiz 11y ago
> If you have "func bar() (MyStruct, error)", you cannot do "foo(bar())". You must always assign the result to an intermediate variable. You could embed the error in the MyStruct struct instead, but that goes against Go's grain.
Chaining does work, but obviously the function needs the same signature as the return values, which limits things since most APIs don't accept errors as input. But within your code you can structure it to get error values for things you know you will be chaining. Or create wrappers to make your types chainable.
http://play.golang.org/p/5LHXdJlfIM http://play.golang.org/p/5LHXdJlfIM
- lobster_johnson 11y agoI swear I tried that once, and that it didn't work. Thanks for educating me. Still, having to let every function take an error parameter isn't really an option, generally.
- vorg 11y ago> Or create wrappers to make your types chainable It can't always be done. A generic wrapper only works for functions that return values. It would be nice to have a wrapper that can take any function, e.g. foo in: package main import "fmt" func foo(a ...interface{})interface{}{ if len(a) == 0 { return nil } else if len(a) == 1 { return a[0] } else { return a } } func barbar() (a, b int) { return 1, 2 } func bar() (a int) { return 1 } func baz() { return } func main() { fmt.Println( foo(barbar()) ) // prints: [1, 2] fmt.Println( foo(bar()) ) // prints: 1 fmt.Println( foo(baz()) ) // compile error: baz() used as value } Instead of the compile error, it would be nice if foo accepted baz() as a argument, which would read the array length as 0 and here return nil.