Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/variables.zig

57 lines
1.1 KiB

const std = @import("std");
const testing = std.testing;
var x: i32 = add(10, y);
const y = add(12, 13);
fn add(a: i32, b: i32) i32 {
return a + b;
}
test "global variables" {
testing.expect(x == 35);
testing.expect(y == 25);
comptime testing.expect(y == 25);
}
fn foo() i32 {
const S = struct {
var val: i32 = 12345;
};
S.val += 1;
return S.val;
}
test "namespaced global" {
testing.expect(foo() == 12346);
testing.expect(foo() == 12347);
}
threadlocal var bar: i32 = 12345;
fn testTls(context: void) void {
testing.expect(bar == 12345);
bar += 100;
testing.expect(bar == 12445);
}
test "thread-local variables" {
const thread1 = try std.Thread.spawn(testTls, {});
const thread2 = try std.Thread.spawn(testTls, {});
testTls({});
thread1.wait();
thread2.wait();
}
test "local variables" {
var xx: i32 = 1;
comptime var yy: i32 = 1;
yy += 1;
testing.expect(xx == 1);
testing.expect(yy == 2);
if (yy != 2) {
@compileError("invalid value for yy");
}
}