Printing
Here is the shortest way to print a string
_=&@import("std").posix.write(1,"Hello!");
And the shortest way to print anything that isn't a string.
_=&@import("std").io.getStdOut().writer().print("{}",.{12345});
Note that the string printer, posix.write
, takes a number as its first argument. If the number is 2, it prints to stderr, which code.golf ignores, so this can be used for conditional printing. Passing any number other than 1 or 2 crashes the program.
Looping
For looping with an incrementing variable, iterating indexes of an array (usually a string) is often better than a while loop
var a:u8=0;while(a<10):(a+=1)try@import("std").io.getStdOut().writer().print("{}\n",.{a}); // 90 bytes
for(" "**10)|_,b|try@import("std").io.getStdOut().writer().print("{}\n",.{b}); // 78 bytes
For a variable-length loop, this requires taking a slice since arrays can only be multiplied by constants. Note that the array needs to be large enough to reach the largest loop you might need.
var L:u8=7;
for((" "**10)[0..L])|_,b|try@import("std").io.getStdOut().writer().print("{}\n",.{b});
Variable declarations
When declaring more than one variable of the same type, it is often good to avoid declaring the type each time.
var a:u8=0;var b:u8=0;
vs.
var a:u8=0;var b=a;
Usize
Don't declare a variable as usize
, u64
is the same thing
var x:usize=0;
var x:u64=0;