从 goroutine func 发出修改映射
Issue modifying map from goroutine func
scores := make(map[string]int)
percentage := make(map[string]float64)
total := 0
for i, ans := range answers {
answers[i] = strings.ToLower(ans)
}
wg := sync.WaitGroup{}
go func() {
wg.Add(1)
body, _ := google(question)
for _, ans := range answers {
count := strings.Count(body, ans)
total += count
scores[ans] += 5 // <------------------- This doesn't work
}
wg.Done()
}()
这是一段代码,我的问题是,我无法修改分数,我试过使用指针,我试过正常操作,我试过将它作为参数传递。
import "sync"
A WaitGroup waits for a collection of goroutines to finish. The main
goroutine calls Add to set the number of goroutines to wait for. Then
each of the goroutines runs and calls Done when finished. At the same
time, Wait can be used to block until all goroutines have finished.
您向我们提供了 non-working 代码片段。参见 How to create a Minimal, Complete, and Verifiable example.
据推测,您对 sync.WaitGroup
的使用看起来很奇怪。例如,只需按照 sync.Waitgroup 文档中的说明进行操作,我希望得到更类似于以下内容的内容:
package main
import (
"fmt"
"strings"
"sync"
)
func google(string) (string, error) { return "yes", nil }
func main() {
question := "question?"
answers := []string{"yes", "no"}
scores := make(map[string]int)
total := 0
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
body, _ := google(question)
for _, ans := range answers {
count := strings.Count(body, ans)
total += count
scores[ans] += 5 // <-- This does work
}
}()
wg.Wait()
fmt.Println(scores, total)
}
游乐场:https://play.golang.org/p/sZmB2Dc5RjL
输出:
map[yes:5 no:5] 1
scores := make(map[string]int)
percentage := make(map[string]float64)
total := 0
for i, ans := range answers {
answers[i] = strings.ToLower(ans)
}
wg := sync.WaitGroup{}
go func() {
wg.Add(1)
body, _ := google(question)
for _, ans := range answers {
count := strings.Count(body, ans)
total += count
scores[ans] += 5 // <------------------- This doesn't work
}
wg.Done()
}()
这是一段代码,我的问题是,我无法修改分数,我试过使用指针,我试过正常操作,我试过将它作为参数传递。
import "sync"
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
您向我们提供了 non-working 代码片段。参见 How to create a Minimal, Complete, and Verifiable example.
据推测,您对 sync.WaitGroup
的使用看起来很奇怪。例如,只需按照 sync.Waitgroup 文档中的说明进行操作,我希望得到更类似于以下内容的内容:
package main
import (
"fmt"
"strings"
"sync"
)
func google(string) (string, error) { return "yes", nil }
func main() {
question := "question?"
answers := []string{"yes", "no"}
scores := make(map[string]int)
total := 0
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
body, _ := google(question)
for _, ans := range answers {
count := strings.Count(body, ans)
total += count
scores[ans] += 5 // <-- This does work
}
}()
wg.Wait()
fmt.Println(scores, total)
}
游乐场:https://play.golang.org/p/sZmB2Dc5RjL
输出:
map[yes:5 no:5] 1