Hi:
Please check this code snippet:
package main
import (
"fmt"
"time"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func main() {
fmt.Println("use values:")
// use values in range loop and go rountines
values := []field{{"one"},{"two"},{"three"}}
for _, v := range values {
go v.print()
}
time.Sleep(time.Second)
fmt.Println()
fmt.Println("use pointers:")
// use pointers in range loop and go rountines
poniters := []*field{{"one"},{"two"},{"three"}}
for _, v := range poniters {
go v.print()
}
time.Sleep(time.Second)
}
Link here: https://play.golang.org/p/cdryPmyWt5
The code above is going to check the differences between pointers and
values in a for loop, while go statement is also used at the same time. For
code:
values := []field{{"one"},{"two"},{"three"}}
for _, v := range values {
go v.print()
}
we know that the console will print *three three three* as result, because
for loop runs into its end before go routines start executing, which write
*v* as the last element of the slice. But what about pointers?
poniters := []*field{{"one"},{"two"},{"three"}}
for _, v := range poniters {
go v.print()
}
It seems to print* one two three*, why?
Thanks.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.