sync....Once...https://play.golang.org/p/GRnbfUG4nut


(Cherolyn Lexvold) #1

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

What’s wrong here?


(Norbert Melzer) #2

You can not use := and loops outside of a function body.


(Gonzalo Sayago) #3

A Closing brace!
https://play.golang.org/p/qqoTDGc7gde


(Qi Yin) #4
package main

import (
	"fmt"
	"sync"
)

func main() {
	fmt.Println("Hello, playground")

	var once sync.Once
	onceBody := func() {
		fmt.Println("Only once")
	}
	done := make(chan bool)
	for i := 0; i < 10; i++ {
		go func() {
			once.Do(onceBody)
			done <- true
		}()
	}
	for i := 0; i < 10; i++ {
		<-done
	}
}

This is that the main function is not closed correctly, resulting in the content of the function body after the function} word.

It is recommended to use the format function to format the code to get a clear code style.


(Cherolyn Lexvold) #5

How would I correct this?


(Norbert Melzer) #6

There have already been some spoilers and corrected code in the other responses, also you really should know by today how you can write a function or move code from the outer scope into a function.


(Cherolyn Lexvold) #7

Still learning. Such as I am. I have to say, I’m doing my best.
I appreciate your continued valuable help in spite of the fact that I seem to irritate you.

I don’t know what that means.

What exactly is the function body in that code and is it the same as the “scope”?

// } Commented
Why?

And why did you add the brace in the location where you added it?


(Gonzalo Sayago) #8

The main function executes the code that is inside the braces!


(Cherolyn Lexvold) #9

Are you referring to onceBody := func()?

Funny, when I removed fmt.Println(“Hello, playground”)
}
and added a closing brace, it worked. :sweat_smile:


(Norbert Melzer) #10

Thats basically what we have told you to do…

Dunno, I just read the error message and looked briefly at the mentioned line.

Once I see the problem, I drop most of the stuff from that line from my mind, especially if its not my own code.