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.
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 mean in the same context then, no.
So I think that means I was asking about execution in the same context (as in memory context), unless you mean stack frame by context, in which case, I think i understand that because the caller returns the value of the deferred, they are in the same stack frame, and nothing else could insert in that frame between them. I'm not sure you know what i mean, but do i have it about right?
I don't really understand this, but i think I'm getting somewhere.
This simple example should explain everything:
package main
import "fmt"
func function1() {
defer fmt.Println("function1: defer a")
fmt.Println("function1: inside")
defer fmt.Println("function1: defer b")
}
func main() {
fmt.Println("main: before function1")
function1()
fmt.Println("main: after function1")
}
Here is the output: main: before function1
function1: inside
function1: defer b
function1: defer a
main: after function1
All defers run in LIFO order at the point when a function returns before the function returns execution back to the caller.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.
Go coroutines (goroutines) are functions invoked with the "go" keyword. These cannot be stopped or resumed, but might be (possibly) executed on a different thread. In any case, they are not guaranteed to be executed immediately in the normal flow of the code.
I'd say more like the equivalent of a "finally" clause (or more) for your whole function.
Though not sure about the "executed in reverse order part" -- what's "in reverse order" about Defer? Except if you mean that multiple defers get executed "last seen first"...
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;
}