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

Why is the loop index declared as let, not let mut ? #686

Closed
AuroraLantean opened this issue Oct 30, 2024 · 2 comments
Closed

Why is the loop index declared as let, not let mut ? #686

AuroraLantean opened this issue Oct 30, 2024 · 2 comments
Labels
documentation Improvements or additions to documentation move-and-smart-contracts All content under https://aptos.dev/en/build/smart-contracts

Comments

@AuroraLantean
Copy link

Url

https://aptos.dev/en/build/smart-contracts/book/loops

Describe the content issue

From the Loop doc page:

  fun sum(n: u64): u64 {
    let sum = 0;
    let i = 1; // <==  WHY is this declared as `let`, not `let mut` ???
    while (i <= n) {
      sum = sum + i;
      i = i + 1
    };
    sum
  }

Section

move-and-smart-contracts

@AuroraLantean AuroraLantean added the documentation Improvements or additions to documentation label Oct 30, 2024
@github-actions github-actions bot added the move-and-smart-contracts All content under https://aptos.dev/en/build/smart-contracts label Oct 30, 2024
Copy link

@aptos-labs/move-eng

@jmintuitive
Copy link
Contributor

In Move, let is the syntax for initializing a variable instead of let mut. const initializes a constant.

References:

  1. This explains how Move uses a let syntax for variables you can change: https://aptos.dev/en/build/smart-contracts/book/variables#assignments.
  2. Constants are initialized with const: https://aptos.dev/en/build/smart-contracts/book/constants

I tested locally in a Move contract, and the looping code above worked to print 1, 2, 3.

Script that was tested:

    #[test()]
    public entry fun test_loops() {
        let n = 3;

        let sum = 0;
        let i = 1;
        while (i <= n) {
            sum = sum + i;
            debug::print(&i);
            i = i + 1;
        };
    }

Result:

INCLUDING DEPENDENCY AptosFramework
INCLUDING DEPENDENCY AptosStdlib
INCLUDING DEPENDENCY MoveStdlib
BUILDING HelloBlockchainExample
Running Move unit tests
[debug] 1
[debug] 2
[debug] 3
[ PASS    ] 0x285cb83ec8ab29b459b0d2997e1d0c06d83ff1faefa9521c4068be483f16dd02::message::test_loops
Test result: OK. Total tests: 1; passed: 1; failed: 0
{
  "Result": "Success"
}

@hariria hariria closed this as completed Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation move-and-smart-contracts All content under https://aptos.dev/en/build/smart-contracts
Projects
None yet
Development

No branches or pull requests

3 participants