aptos-labs / developer-docs

Source for the Aptos developer docs
https://aptos.dev
Apache License 2.0
889 stars 98 forks source link

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

Closed AuroraLantean closed 3 weeks ago

AuroraLantean commented 3 weeks ago

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

github-actions[bot] commented 3 weeks ago

@aptos-labs/move-eng

jmintuitive commented 3 weeks ago

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