onflow/cadence

Support using references in loops

Closed this issue · 3 comments

Issue to be solved

Currently, for-each loop only supports arrays, and doesn't support array references.
i.e:

var arrayRef: &[String] = ...

for element in arrayRef {    // Error

}

However, with the mutability changes, given fields can now return references, it would be useful to be able to use array references in loops as well.

Suggested Solution

Allow using array references in for loops.

for v in arrayRef {}

For an array of type [T], the type of the loop-variable v would be:

  • The concrete type T, if the array element type T is a primitive.
  • A reference type &T, if the array element is a container type.

This is to be consistent with the member access semantics: https://github.com/onflow/flips/blob/120b8aa473e5040db2b99034d2118fb78d053cdf/cadence/20230517-member-access-semnatics.md

We might want to get this implemented as part of Cadence 1.0 to ease with the transition and not require developers to migrate their contracts to worse versions (like in onflow/flow-core-contracts#382 (comment))

For an array of type [T], the type of the loop-variable v would be:

The concrete type T, if the array element type T is a primitive.
A reference type &T, if the array element is a container type.

second part confused me a little, why &T ?

I feel:

var arrayRef: &[[String]] = ...

for element in arrayRef { 
     //element here should be [String]
}

This is beacsue with the member-access semantics change, arrayRef[i] would return &[String]. So we would need to keep the same semantics in the loop as well.

More details are available here: https://developers.flow.com/next/cadence/language/references#field-and-index-access