* etienne.da...@gmail.com <etienne.da...@gmail.com> [171011 03:14]:
> I was thinking of your answer, and I don't understand when you say:
> 
> > within a func type literal such as `func() (x int)`, the scope of the 
> > parameters and results is restricted to the type literal itself.
> >
> Because the following code works, so the scope of a parameter is different 
> than the scope of a result.
> 
> const N = 10
> 
> func main() {
>     f := fibo(0)
>     for i := 0; i < N; i++ {
>         fmt.Println(f())
>     }
> }
> 
> func fibo(x int) func() int {
            ^

Here, x is in the scope of fibo and during execution of fibo exists as a
variable with that name.  Within fibo it can be bound in a closure
created by fibo.

>     y := 1
>     return func() int {
>         defer func() { x, y = y, x+y }()
>         return x
>     }
> }
> 
> On Tuesday, 10 October 2017 17:08:49 UTC+2, Etienne Daspe wrote:
> > On Tuesday, 10 October 2017 16:58:43 UTC+2, Ian Lance Taylor wrote:
> >> On Tue, Oct 10, 2017 at 7:22 AM,  <etienn...@gmail.com> wrote: 
> >> > // fibo2 doesn't compile because x is undefined in the function 
> >> returned. 
> >> > //func fibo2() func() (x int) { 
                              ^

Here, x is a placeholder name within a type literal; it is not within
the scope of fibo.  This could be rewritten as:

type result func() (x int)
func fibo2() result {

Note that x is neither an argument nor a result of fibo2 (either way the
code is written).  The name x in fibo2 is part of the description of the
type of the result of fibo2, it is not the name of an argument or result
of fibo2.  This is what Ian was saying below.

> >> > //    y := 1 
> >> > //    return func() int { 
> >> > //        defer func() { x, y = y, x+y }() 
> >> > //        return x 
> >> > //    } 
> >> > //} 
> >>
> >> In the commented out code, x is a result variable, but only for 
> >> `func() (x int)`.  x is not a result variable for fibo2. 
> >>
> >> To put it differently, within a func type literal such as `func() (x 
> >> int)`, the scope of the parameters and results is restricted to the 
> >> type literal itself. 
> >>
> >> Ian 

...Marvin

-- 
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 golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to