在循环迭代器变量上使用goroutine

时间:2017-12-01 00:47:42

标签: loops go

我正在读取循环迭代器上的goroutine经常导致循环赋值中的最后一个值用于每次迭代。例如。 https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables

然而,这只会发生在闭包上,例如:匿名函数?

我似乎无法通过此示例https://play.golang.org/p/lpZ-yD1mHu

重现此问题

当我使用这样的匿名函数时,它会重新创建问题https://play.golang.org/p/mDa0Z6mUP8

1 个答案:

答案 0 :(得分:4)

  

然而,这只是封闭的问题,例如匿名函数?

是。

之间的区别
go speak(c)

go func() {
    speak(c)
}()

是,前者在新的goroutine中使用speak来调用c。然而,在后一种情况下,匿名函数捕获c但是变量c本身(通过引用¹),并在稍后的某个时间点调用speak c具有此时的'========================================= Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim str As String Dim cboTemp As OLEObject Dim ws As Worksheet Set ws = ActiveSheet On Error GoTo errHandler If Target.Count > 1 Then GoTo exitHandler Set cboTemp = ws.OLEObjects("ComboBox1") On Error Resume Next If cboTemp.Visible = True Then With cboTemp .Top = 10 .Left = 10 .ListFillRange = "Treatment" .LinkedCell = Target.Address .Visible = False .Value = "" End With End If On Error GoTo errHandler If Target.Validation.Type = 3 Then 'if the cell contains a data validation list Application.EnableEvents = False 'get the data validation formula str = Target.Validation.Formula1 str = Right(str, Len(str) - 1) With cboTemp 'show the combobox with the list .Visible = True .Left = Target.Left .Top = Target.Top .Width = Target.Width + 15 .Height = Target.Height + 5 .ListFillRange = ws.Range(str).Address .LinkedCell = Target.Address End With cboTemp.Activate 'open the drop down list automatically Me.ComboBox1.DropDown End If exitHandler: Application.ScreenUpdating = True Application.EnableEvents = True Exit Sub errHandler: Resume exitHandler End Sub '==================================== 'Optional code to move to next cell if Tab or Enter are pressed 'from code by Ted Lanham '***NOTE: if KeyDown causes problems, change to KeyUp 'Table with numbers for other keys such as Right Arrow (39) 'https://msdn.microsoft.com/en-us/library/aa243025%28v=vs.60%29.aspx Private Sub ComboBox1_KeyDown(ByVal _ KeyCode As MSForms.ReturnInteger, _ ByVal Shift As Integer) Select Case KeyCode Case 9 'Tab ActiveCell.Offset(0, 1).Activate Case 13 'Enter ActiveCell.Offset(1, 0).Activate Case Else 'do nothing End Select End Sub '==================================== 值。

¹:golang中没有“引用”,我不确定这是如何实现的,但就好像它们引用了原始变量一样。