Variables in Chapel

In Chapel, variables are explicitly declared and used by the compiler to check type-correctness of function calls.

use IO;

proc main() {
    // `var` declares 1 or more variables.
    var a = "initial";
    writeln(a);

    // You can declare multiple variables at once.
    var b, c: int = 1, 2;
    writeln(b, " ", c);

    // Chapel will infer the type of initialized variables.
    var d = true;
    writeln(d);

    // Variables declared without a corresponding
    // initialization are default-initialized. For example,
    // the default value for an `int` is `0`.
    var e: int;
    writeln(e);

    // Chapel doesn't have a shorthand declaration syntax like
    // Go's `:=`. Instead, you can use type inference with `var`.
    var f = "apple";
    writeln(f);
}

To run the program, save it as variables.chpl and use the Chapel compiler:

$ chpl variables.chpl -o variables
$ ./variables
initial
1 2
true
0
apple

In Chapel:

  1. Variables are declared using the var keyword.
  2. Type annotations are optional when initializing variables, as Chapel can infer types.
  3. Multiple variables can be declared and initialized in a single line.
  4. Variables without explicit initialization are default-initialized.
  5. Chapel doesn’t have a shorthand declaration syntax like :=, but type inference with var achieves a similar result.
  6. The writeln function is used for printing to the console, similar to fmt.Println in Go.

Chapel’s approach to variables is similar to Go’s, with some syntax differences. Both languages emphasize static typing and provide type inference capabilities.