
Functions
Functions are introduced by the func keyword.
Return type, if any, comes after parameters. The return does as you expect.
func square(f float) float { return f*f }
A function can return multiple values. If so, the return types are a parenthesized list.
func MySqrt(f float) (float, bool) {
if f >= 0 { return math.Sqrt(f), true }
return 0, false
}
Functions [...]
Functions
Functions are introduced by the func keyword.
Return type, if any, comes after parameters. The return does as you expect.
func square(f float) float { return f*f }
A function can return multiple values. If so, the return types are a parenthesized list.
func MySqrt(f float) (float, bool) {
if f >= 0 { return math.Sqrt(f), true }
return 0, false
}
Functions with result variables
The result “parameters” are actual variables you can use if you name them.
func MySqrt(f float) (v float, ok bool) {
if f >= 0 { v,ok = math.Sqrt(f),true }
else { v,ok = 0,false }
return v,ok
}
The result variables are initialized to “zero”
(0,0.0, false etc. according to type; more in a sec).
func MySqrt(f float) (v float, ok bool) {
if f >= 0 { v,ok = math.Sqrt(f),true }
return v,ok
}
The empty return
Finally, a return with no expressions returns the existing value of the result variables. Two more versions of MySqrt:
func MySqrt(f float) (v float, ok bool) {
if f >= 0 { v,ok = math.Sqrt(f),true }
return // must be explicit
}
func MySqrt(f float) (v float, ok bool) {
if f < 0 { return } // error case
return math.Sqrt(f),true
}
Function literals
As in C, functions can’t be declared inside functions -but function literals can be assigned to variables.
func f() {
for i := 0; i < 10; i++ {
g := func(i int) { fmt.Printf(”%d”,i) };
g(i);
}
}
Function literals are closures
Function literals are indeed closures.
func adder() (func(int) int) {
var x int;
return func(delta int) int {
x += delta;
return x
}
}
var f = adder();
fmt.Print(f(1));
fmt.Print(f(20));
fmt.Print(f(300));
Prints 1 21 321 – accumulating in f’s x
No related posts.






Leave Your Response