1. 程式人生 > 實用技巧 >golang 條件語句 for range 分析

golang 條件語句 for range 分析

for range 作為 golang中的語法糖提供了便利操作;

對於for range 支援 的資料型別包含:

  • 陣列以及指向陣列的指標
  • 切片
  • 字典
  • 通道
  • 字串

在range的語法糖中提供了一下特殊操作

https://blog.cyeam.com/golang/2018/10/30/for-interals

https://garbagecollected.org/2017/02/22/go-range-loop-internals/

https://github.com/golang/gofrontend/blob/e387439bfd24d5e142874b8e68e7039f74c744d7/go/statements.cc#L5579

在原始碼中的lower_range_slice 遍歷切片的註釋中存在

// The loop we generate:
  //   for_temp := range
  //   len_temp := len(for_temp)
  //   for index_temp = 0; index_temp < len_temp; index_temp++ {
  //           value_temp = for_temp[index_temp]
  //           index = index_temp
  //           value = value_temp
  //           original body
  //   }
  //

  展示的為range語法糖編譯為golang語句後真實執行

可以看到在真實執行range語法時,實際是先對原始資料進行了賦值操作,在真正執行迭代時,實際操作的是副本資料