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

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

What’s wrong here?

2 Likes

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

3 Likes

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

3 Likes
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.

3 Likes

How would I correct this?

2 Likes

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.

2 Likes

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?

2 Likes

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

3 Likes

Are you referring to onceBody := func()?

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

2 Likes

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.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.