golang Unusual Go Construct: Creating reusable Name: name := name .... Somethiing -


i saw construct somewhere reusing "name" when sending data function.

i working database , need send lot of "named" buffers processed. construct seems perfect, can not make work , can not remember saw discussed.

any appreciated.

the jist of text each time used contruct name used on , over, each instance own it's own collection.

all remember name := name ..then something. lost here.

you're referring creating copies of loop variables. normally, in code:

for := 0; < 100; i++ {     go func() {         fmt.println(i)     } } 

i reference loop variable in goroutines, if goroutines spawn , loop keeps going before call fmt.println(i), i different value when call when spawned loop. 1 way around do, mentioned:

for := 0; < 100; i++ {     :=     go func() {         fmt.println(i)     } } 

the added line, i := i, introduces local variable called i, , sets equal loop variable i. these 2 distinct variables. might j := i , use j instead. tend think using i := i more confusing, people prefer it. in case, given it's local variable, there's different instance of per loop, means each goroutine sees own unique instance won't changed.

while idiom can found in effective go (search "req := req" on page), let me clear something: this confusing , should avoided. don't know why go authors thought idea introduce idiom, and, in opinion, should avoided. why? because there's cleaner way accomplish same thing more understandable:

for := 0; < 100; i++ {     go func(i int) {         fmt.println(i)     }(i) } 

in version, anonymous function takes single integer argument, , when spawned in goroutine, loop variable i passed argument. people have more solid understanding of these semantics, , it's easier see , understand why works. if still confusing, suggest changing argument name:

for := 0; < 100; i++ {     go func(j int) {         fmt.println(j)     }(i) } 

i think these 2 approaches more understandable , should used instead of example mentioned.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -