for

Odin only has one looping construct, the for loop.

The basic for loop (C-like) has three components separated by semicolons:

  • the initial statement: executed before the first iteration
  • the condition expression: evaluated before every iteration
  • the post statement: executed at the end of every iteration

The initial statement will often be variable declaration or an assignment, and the variables declared there are only visible in the scope of the for statement.

The loop with stop iterating once the boolean condition is false.

#import "fmt.odin";
main :: proc() {
    product := 1;
    for i := 1; i < 10; i++ {
        product *= i;
    }
    fmt.println(product);
}

Note: Unlike other languages, there are no parentheses surrounding these components and the braces { } are required.

The initial and post statement are optional.

triangle := 1;
for ; triangle < 200; {
    triangle += triangle;
}

The semicolons can be removed, and this is equivalent to C's while loop

triangle := 1;
for triangle < 200 {
    triangle += triangle;
}

If the condition is omitted too, the loop with loops forever.

for {
// Neverending story
// Nana na nana na nana na
}

for in

Most of the time, a loop is used to iterate across a type. This can be done with the for in statement. The types which can be iterated across are:

  • arrays
  • slices
  • vectors
  • dynamic arrays
  • maps
  • strings
x := [5]int{1, 4, 9, 16, 25};
for elem in x {
    fmt.println(elem);
}

// Optional index
for elem, idx in x {
    fmt.printf("x[%d] == %v\n", idx, elem);
}

// Ignore the value
for _, i in x {
    fmt.println(x[i]);
}

With maps, the value and index becomes the value and key.

m := map[string]int{"Apple" = 1, "Beans" = 3, "Cool" = 1337};
for val, key in m {
    fmt.printf("%v at %v\n", val, key);
}

When iterating across a string, instead of each byte, the loop assumes that the string is encoded as a UTF-8 string and returns the series of Unicode code points, each as a rune. Thus, the index value does equate to the byte index in the string, rather the code point index.

str := "Hellope, 世界";
for r in str {
    fmt.printf("%c\n", r);
}

Number ranges

// C-style loop
for i := 0; i < 10; i++ {
}

// Range-style
for i in 0..<10 {
}

// C-style loop
for i := 0; i <= 12; i++ {
}

// Range-style
for i in 0..12 {
}

The latter example is similar to the former loop. The difference between the two is that the i in the range loop is just a value that cannot be addressed whilst in the former, i is a variable which can be modified.

.. is an open interval, where the right hand side value is included in that range.

..< is a half-closed interval, where the right hand side value is not included in that range.

The .. or ..< syntax does not allow for different step sizes nor iterated "downwards" (as of yet).

results matching ""

    No results matching ""