https://play.golang.org/p/GRnbfUG4nut
What’s wrong here?
You can not use :=
and loops outside of a function body.
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.
How would I correct this?
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.
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?
The main function executes the code that is inside the braces!
Are you referring to onceBody := func()?
Funny, when I removed fmt.Println(“Hello, playground”)
}
and added a closing brace, it worked.
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.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.