dongpi3237 2017-08-29 14:31
浏览 20

字符串切片的范围不一致

This code:

import "fmt"
import "time"
func main() {
    string_slice:=[]string{"a","b","c"}

    for _,s:=range string_slice{
        go func(){
            time.Sleep(1*time.Second)
            fmt.Println(s)
        }()
    }

    time.Sleep(3*time.Second)
}

produces the output "c c c", while this code:

import "fmt"
func main() {
    string_slice:=[]string{"a","b","c"}

    for _,s:=range string_slice{
        s="asd"
        fmt.Println(s)
    }
    fmt.Println(string_slice)
}

produces the output "[a b c]"

The first one would suggest that for range iterates over references (which it should not), and the second one suggests that it iterates over copies of values (which it should).

Why doesn't the first one produce the output "a b c"?

  • 写回答

1条回答 默认 最新

  • douzhong4222 2017-08-29 15:19
    关注

    When uses goroutine you must assume that it will running in parallelo. So in this case might occur 'c c c' as too 'b b b' or 'a a a'

    On run in 3 times this code:

    for _,s:=range string_slice \un t0, t1, t2 
    

    You will send for running 3 times this code:

    go func(){
      fmt.Println(s)
    }()//send in t0, t1, t2
    

    So, might occur of func() start running in t2, per example. In this case the result will 'c c c' because s equals latest value (string_slice[2]).

    The solution is copy value by func params:

    for _, s := range string_slice{
        go func(x string){
            time.Sleep(1*time.Second)
            fmt.Println(x)
        }(s)
    }
    

    Or create new value per iteration

    //creating new value per iteration
    for i := range string_slice{
        s := string_slice[i]
        go func(){
            time.Sleep(1*time.Second)
            fmt.Println(s)
        }()
    }
    

    See working in https://play.golang.org/p/uRD6Qy6xSw

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看