Hands-on exercise...create a func which “encloses” the scope of a variable:


(Cherolyn Lexvold) #1

https://play.golang.org/p/ceO6iMgUo43

What do they mean…expected expression. Anything wrong with defining a func? That’s what I’m trying to do there


(Cherolyn Lexvold) #2

Second attempt:

https://play.golang.org/p/1ElNBeftv9i

What in the world?


(Benjamin Radovsky) #3

Hi @cherilexvold1974 ,

Your first example should be:

package main

import (
	"fmt"
)

func main() {
	z := StanleyCup()
	fmt.Println(z()) // You need to call the function here.
}

func StanleyCup() func() string {
	var p string
	return func() string {
		fmt.Println("No Blackhawks")
		return p
	}
}

In your second example, you also need to call the function, for example:

fmt.Println(m())

(Cherolyn Lexvold) #4

Okay, from what you explained in the first example, I did this:
https://play.golang.org/p/Znzj2pytZUd
The difference I saw in your code was

fmt.Println(z())

I’m still getting an error message when I format.
What am I missing?

In the second example, I got it!
https://play.golang.org/p/5OT1BvKZDrc

Thanks!


(Cherolyn Lexvold) #5

Can I , for the lack of a better word, expand https://play.golang.org/p/5OT1BvKZDrc
so that it prints out 1
2
3
4