Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support using references in loops #2784

Closed
SupunS opened this issue Sep 14, 2023 · 3 comments
Closed

Support using references in loops #2784

SupunS opened this issue Sep 14, 2023 · 3 comments
Assignees
Labels

Comments

@SupunS
Copy link
Member

SupunS commented Sep 14, 2023

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

@turbolent
Copy link
Member

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))

@bluesign
Copy link
Contributor

bluesign commented Sep 14, 2023

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]
}

@SupunS
Copy link
Member Author

SupunS commented Sep 14, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants