by alexhornbake · 9y ago · 0 comments
Returning a new unnamed variable for every return will cause all of the unnamed variables to be allocated.
It's interesting, I don't use this feature of the language... my default way to write this would have been:
func NoNamedReturnParams(i int) (*objectInfo) {
obj := &objectInfo{}
if i == 1 {
// Do one thing
return obj
}
if i == 2 {
// Do another thing
return obj
}
if i == 3 {
// Do one more thing still
return obj
}
// Normal return
return obj
}It really hammers home the concept that a function is a transformation, and of what into what. And I think this syntax would probably encourage pure functions. And it's so useful to allocate the return in the top line. I really like go.
Named returns are a Go thing mainly because of defer.
Try it and see: https://play.golang.org/p/1ozFWDj15a
If you had a variable declared in a block just before return, then you return it, you have no way to modify it in defer.
I personally don't like this style of code, but I can see some uses.
add1 = map (+1)
OTOH they also split the signature and function "header" so that you don't need to remove the "noise" to get the bare signature e.g. add1 :: (Num a) => [a] -> [a]
add1 = map (+1)Normal C style declaration
int foo() { return 2; }
Trailing return type. Useful when the return type depends on the parameter types, or is inside the namespace of the function auto foo() -> int { return 2; }
Automated type deduction. Increasingly the choice when possible auto foo() { return 2; } int foo(x,y)
{
return baz(x,y);
}
bar(x,y,z)
short x;
int z;
{
return x+y+z;
}
baz(x,y,z)
{
return 42;
}