Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

runtime: value copy issue #29626

Closed
sunvim opened this issue Jan 9, 2019 · 3 comments
Closed

runtime: value copy issue #29626

sunvim opened this issue Jan 9, 2019 · 3 comments

Comments

@sunvim
Copy link

@sunvim sunvim commented Jan 9, 2019

What version of Go are you using (go version)?

go 1.10.3 , go 1.10.4 , go 1.11

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

windows 10 x86_64

What did you do?

package main

import "fmt"

type Person struct {
Name string
Age int
}

func main() {
m := make(map[string]Person, 2)
m["1"] = Person{"n1", 11}
m["2"] = Person{"n2", 12}
for _, v := range m {
go output(&v)
}
select {}
}

func output(v *Person) {
fmt.Println(v)
}

What did you expect to see?

&{n1,11}
&{n2,12}

What did you see instead?

&{n2 12}
&{n2 12}

@agnivade

This comment has been minimized.

Copy link
Contributor

@agnivade agnivade commented Jan 9, 2019

Please see - https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables

To fix it, use -

go func(v Person){output(&v)}(v)

@agnivade agnivade closed this Jan 9, 2019
@sunvim

This comment has been minimized.

Copy link
Author

@sunvim sunvim commented Jan 10, 2019

Please see - https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables

To fix it, use -

go func(v Person){output(&v)}(v)

yes, I know how to fix it.

but pass value by this way, the perfermance maybe a bit effect.

@mattn

This comment has been minimized.

Copy link
Member

@mattn mattn commented Jan 10, 2019

Then, please try this.

func main() {
	m := make(map[string]Person, 2)
	m["1"] = Person{"n1", 11}
	m["2"] = Person{"n2", 12}
	for _, v := range m {
		v := v // ADD THIS
		go output(&v)
	}
	select {}
}
@golang golang locked and limited conversation to collaborators Jan 10, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.