Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
β |
---|---|---|---|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/30.vectors-splat-scalar.zig | // hide-start
const expect = @import("std").testing.expect;
const meta = @import("std").meta;
//hide-end
test "vector * scalar" {
const x: @Vector(3, f32) = .{ 12.5, 37.5, 2.5 };
const y = x * @as(@Vector(3, f32), @splat(2));
try expect(meta.eql(y, @Vector(3, f32){ 25, 75, 5 }));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/16.struct-defaults.zig | const Vec4 = struct { x: f32 = 0, y: f32 = 0, z: f32 = 0, w: f32 = 0 };
test "struct defaults" {
const my_vector = Vec4{
.x = 25,
.y = -50,
};
_ = my_vector;
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/19-floats.mdx | import CodeBlock from "@theme/CodeBlock";
import FloatsWidening from "!!raw-loader!./19.floats-widening.zig";
import FloatsLiterals from "!!raw-loader!./19.floats-literals.zig";
import FloatsHexUnderscores from "!!raw-loader!./19.floats-hex-underscores.zig";
import FloatsConversion from "!!raw-loader!./19.floats-conversion.zig";
# Floats
Zig's floats are strictly IEEE-compliant unless
[`@setFloatMode(.Optimized)`](https://ziglang.org/documentation/master/#setFloatMode)
is used, which is equivalent to GCC's `-ffast-math`. Floats coerce to larger
float types.
<CodeBlock language="zig">{FloatsWidening}</CodeBlock>
Floats support multiple kinds of literal.
<CodeBlock language="zig">{FloatsLiterals}</CodeBlock>
Underscores may also be placed between digits.
<CodeBlock language="zig">{FloatsHexUnderscores}</CodeBlock>
Integers and floats may be converted using the built-in functions
[`@floatFromInt`](https://ziglang.org/documentation/0.12.0/#floatFromInt) and
[`@intFromFloat`](https://ziglang.org/documentation/0.12.0/#intFromFloat).
[`@floatFromInt`](https://ziglang.org/documentation/0.12.0/#floatFromInt) is
always safe, whereas
[`@intFromFloat`](https://ziglang.org/documentation/0.12.0/#intFromFloat) is
detectable illegal behaviour if the float value cannot fit in the integer
destination type.
<CodeBlock language="zig">{FloatsConversion}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.error-set-merge.zig | const A = error{ NotDir, PathNotFound };
const B = error{ OutOfMemory, PathNotFound };
const C = A || B;
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-returning-type.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
fn Matrix(
comptime T: type,
comptime width: comptime_int,
comptime height: comptime_int,
) type {
return [height][width]T;
}
test "returning a type" {
try expect(Matrix(f32, 4, 4) == [4][4]f32);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/18.integer-widening.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "integer widening" {
const a: u8 = 250;
const b: u16 = a;
const c: u32 = b;
try expect(c == a);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/16-structs.mdx | import CodeBlock from "@theme/CodeBlock";
import Struct from "!!raw-loader!./16.struct.zig";
import StructDefaults from "!!raw-loader!./16.struct-defaults.zig";
import StructDeclarations from "!!raw-loader!./16.struct-declarations.zig";
# Structs
Structs are Zig's most common kind of composite data type, allowing you to
define types that can store a fixed set of named fields. Zig gives no guarantees
about the in-memory order of fields in a struct or its size. Like arrays,
structs are also neatly constructed with `T{}` syntax. Here is an example of
declaring and filling a struct.
<CodeBlock language="zig">{Struct}</CodeBlock>
Struct fields cannot be implicitly uninitialised:
```zig
test "missing struct field" {
const my_vector = Vec3{
.x = 0,
.z = 50,
};
_ = my_vector;
}
```
```
error: missing field: 'y'
const my_vector = Vec3{
^
```
Fields may be given defaults:
<CodeBlock language="zig">{StructDefaults}</CodeBlock>
Like enums, structs may also contain functions and declarations.
Structs have the unique property that when given a pointer to a struct, one
level of dereferencing is done automatically when accessing fields. Notice how,
in this example, `self.x` and `self.y` are accessed in the swap function without
needing to dereference the self pointer.
<CodeBlock language="zig">{StructDeclarations}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/30.vectors-indexing.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "vector indexing" {
const x: @Vector(4, u8) = .{ 255, 0, 255, 0 };
try expect(x[0] == 255);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/28.anonymous-structs-fully-anonymous.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "fully anonymous struct" {
try dump(.{
.int = @as(u32, 1234),
.float = @as(f64, 12.34),
.b = true,
.s = "hi",
});
}
fn dump(args: anytype) !void {
try expect(args.int == 1234);
try expect(args.float == 12.34);
try expect(args.b);
try expect(args.s[0] == 'h');
try expect(args.s[1] == 'i');
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/19.floats-hex-underscores.zig | const lightspeed: f64 = 299_792_458.000_000;
const nanosecond: f64 = 0.000_000_001;
const more_hex: f64 = 0x1234_5678.9ABC_CDEFp-10;
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/03.if-expression.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "if statement expression" {
const a = true;
var x: u16 = 0;
x += if (a) 1 else 2;
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/23.optionals-find.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "optional" {
var found_index: ?usize = null;
const data = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 12 };
for (data, 0..) |v, i| {
if (v == 10) found_index = i;
}
try expect(found_index == null);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/05.for.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "for" {
//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };
for (string, 0..) |character, index| {
_ = character;
_ = index;
}
for (string) |character| {
_ = character;
}
for (string, 0..) |_, index| {
_ = index;
}
for (string) |_| {}
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08-errors.mdx | import CodeBlock from "@theme/CodeBlock";
import ErrorSet from "!!raw-loader!./08.error-set.zig";
import ErrorSetCoercion from "!!raw-loader!./08.error-set-coercion.zig";
import ErrorUnion from "!!raw-loader!./08.error-union.zig";
import ErrorPayloadCapture from "!!raw-loader!./08.error-payload-capture.zig";
import ErrorTry from "!!raw-loader!./08.error-try.zig";
import Errdefer from "!!raw-loader!./08.errdefer.zig";
import ErrorSetInferred from "!!raw-loader!./08.error-set-inferred.zig";
import ErrorSetMerge from "!!raw-loader!./08.error-set-merge.zig";
# Errors
An error set is like an enum (details on Zig's enums later), where each error in
the set is a value. There are no exceptions in Zig; errors are values. Let's
create an error set.
<CodeBlock language="zig">{ErrorSet}</CodeBlock>
Error sets coerce to their supersets.
<CodeBlock language="zig">{ErrorSetCoercion}</CodeBlock>
An error set type and another type can be combined with the `!` operator to form
an error union type. Values of these types may be an error value or a value of
the other type.
Let's create a value of an error union type. Here
[`catch`](https://ziglang.org/documentation/master/#catch) is used, which is
followed by an expression which is evaluated when the value preceding it is an
error. The catch here is used to provide a fallback value, but could instead be
a [`noreturn`](https://ziglang.org/documentation/master/#noreturn) - the type of
`return`, `while (true)` and others.
<CodeBlock language="zig">{ErrorUnion}</CodeBlock>
Functions often return error unions. Here's one using a catch, where the `|err|`
syntax receives the value of the error. This is called **payload capturing**,
and is used similarly in many places. We'll talk about it in more detail later
in the chapter. Side note: some languages use similar syntax for lambdas - this
is not true for Zig.
<CodeBlock language="zig">{ErrorPayloadCapture}</CodeBlock>
`try x` is a shortcut for `x catch |err| return err`, and is commonly used where
handling an error isn't appropriate. Zig's
[`try`](https://ziglang.org/documentation/master/#try) and
[`catch`](https://ziglang.org/documentation/master/#catch) are unrelated to
try-catch in other languages.
<CodeBlock language="zig">{ErrorTry}</CodeBlock>
[`errdefer`](https://ziglang.org/documentation/master/#errdefer) works like
[`defer`](https://ziglang.org/documentation/master/#defer), but only executing
when the function is returned from with an error inside of the
[`errdefer`](https://ziglang.org/documentation/master/#errdefer)'s block.
<CodeBlock language="zig">{Errdefer}</CodeBlock>
Error unions returned from a function can have their error sets inferred by not
having an explicit error set. This inferred error set contains all possible
errors that the function may return.
<CodeBlock language="zig">{ErrorSetInferred}</CodeBlock>
Error sets can be merged.
<CodeBlock language="zig">{ErrorSetMerge}</CodeBlock>
`anyerror` is the global error set, which due to being the superset of all error
sets, can have an error from any set coerced to it. Its usage should be
generally avoided.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/15.enum-methods.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
const Suit = enum {
clubs,
spades,
diamonds,
hearts,
pub fn isClubs(self: Suit) bool {
return self == Suit.clubs;
}
};
test "enum method" {
try expect(Suit.spades.isClubs() == Suit.isClubs(.spades));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/30.vectors-add.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
const meta = @import("std").meta;
test "vector add" {
const x: @Vector(4, f32) = .{ 1, -10, 20, -1 };
const y: @Vector(4, f32) = .{ 2, 10, 0, 1 };
const z = x + y;
try expect(meta.eql(z, @Vector(4, f32){ 3, 0, 20, 0 }));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/09.switch-statement.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "switch statement" {
var x: i8 = 10;
switch (x) {
-1...1 => {
x = -x;
},
10, 100 => {
//special considerations must be made
//when dividing signed integers
x = @divExact(x, 10);
},
else => {},
}
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/04.while-continue-expression.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while with continue expression" {
var sum: u8 = 0;
var i: u8 = 1;
while (i <= 10) : (i += 1) {
sum += i;
}
try expect(sum == 55);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/05-for-loops.mdx | import CodeBlock from "@theme/CodeBlock";
import For from "!!raw-loader!./05.for.zig";
# For loops
For loops are used to iterate over arrays (and other types, to be discussed
later). For loops follow this syntax. Like while, for loops can use `break` and
`continue`. Here, we've had to assign values to `_`, as Zig does not allow us to
have unused values.
<CodeBlock language="zig">{For}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/03.expect.zig | const expect = @import("std").testing.expect;
test "if statement" {
const a = true;
var x: u16 = 0;
if (a) {
x += 1;
} else {
x += 2;
}
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-blocks.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
fn fibonacci(n: u16) u16 {
if (n == 0 or n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
test "comptime blocks" {
const x = comptime fibonacci(10);
const y = comptime blk: {
break :blk fibonacci(10);
};
try expect(y == 55);
try expect(x == 55);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/11.pointers.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn increment(num: *u8) void {
num.* += 1;
}
test "pointers" {
var x: u8 = 1;
increment(&x);
try expect(x == 2);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-switch-capture.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
const Info = union(enum) {
a: u32,
b: []const u8,
c,
d: u32,
};
test "switch capture" {
const b = Info{ .a = 10 };
const x = switch (b) {
.b => |str| blk: {
try expect(@TypeOf(str) == []const u8);
break :blk 1;
},
.c => 2,
//if these are of the same type, they
//may be inside the same capture group
.a, .d => |num| blk: {
try expect(@TypeOf(num) == u32);
break :blk num * 2;
},
};
try expect(x == 20);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-concat-repeat.zig | // hide-start
const expect = @import("std").testing.expect;
const eql = @import("std").mem.eql;
//hide-end
test "++" {
const x: [4]u8 = undefined;
const y = x[0..];
const a: [6]u8 = undefined;
const b = a[0..];
const new = y ++ b;
try expect(new.len == 10);
}
test "**" {
const pattern = [_]u8{ 0xCC, 0xAA };
const memory = pattern ** 3;
try expect(eql(u8, &memory, &[_]u8{ 0xCC, 0xAA, 0xCC, 0xAA, 0xCC, 0xAA }));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/15.enum-declarations.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
const Mode = enum {
var count: u32 = 0;
on,
off,
};
test "hmm" {
Mode.count += 1;
try expect(Mode.count == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/03-if.mdx | import CodeBlock from "@theme/CodeBlock";
import Expect from "!!raw-loader!./03.expect.zig";
import IfExpression from "!!raw-loader!./03.if-expression.zig";
# If Expressions
Zig's if statements accept `bool` values (i.e. `true` or `false`). Unlike languages
like C or Javascript, there are no values that implicitly coerce to bool values.
Here, we will introduce testing. Save the below code and compile + run it with
`zig test file-name.zig`. We will be using the
[`expect`](https://ziglang.org/documentation/master/std/#std.testing.expect)
function from the standard library, which will cause the test to fail if it's
given the value `false`. When a test fails, the error and stack trace will be
shown.
<CodeBlock language="zig">{Expect}</CodeBlock>
If statements also work as expressions.
<CodeBlock language="zig">{IfExpression}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/29.sentinel-termination-ptrcast.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "sentinel termination" {
const terminated = [3:0]u8{ 3, 2, 1 };
try expect(terminated.len == 3);
try expect(@as(*const [4]u8, @ptrCast(&terminated))[3] == 0);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/04.while-continue.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while with continue" {
var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
if (i == 2) continue;
sum += i;
}
try expect(sum == 4);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/06.functions.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn addFive(x: u32) u32 {
return x + 5;
}
test "function" {
const y = addFive(0);
try expect(@TypeOf(y) == u32);
try expect(y == 5);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/07-defer.mdx | import CodeBlock from "@theme/CodeBlock";
import Defer from "!!raw-loader!./07.defer.zig";
import DeferMulti from "!!raw-loader!./07.defer-multi.zig";
# Defer
Defer is used to execute a statement while exiting the current block.
<CodeBlock language="zig">{Defer}</CodeBlock>
When there are multiple defers in a single block, they are executed in reverse
order.
<CodeBlock language="zig">{DeferMulti}</CodeBlock>
Defer is useful to ensure that resources are cleaned up when they are no longer needed.
Instead of needing to remember to manually free up the resource,
you can add a defer statement right next to the statement that allocates the resource.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-while-error-union.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
var numbers_left2: u32 = undefined;
fn eventuallyErrorSequence() !u32 {
return if (numbers_left2 == 0) error.ReachedZero else blk: {
numbers_left2 -= 1;
break :blk numbers_left2;
};
}
test "while error union capture" {
var sum: u32 = 0;
numbers_left2 = 3;
while (eventuallyErrorSequence()) |value| {
sum += value;
} else |err| {
try expect(err == error.ReachedZero);
}
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25-payload-captures.mdx | import CodeBlock from "@theme/CodeBlock";
import PayloadCapturesOptionalIf from "!!raw-loader!./25.payload-captures-optional-if.zig";
import PayloadCapturesErrorUnionIf from "!!raw-loader!./25.payload-captures-error-union-if.zig";
import PayloadCapturesWhileOptional from "!!raw-loader!./25.payload-captures-while-optional.zig";
import PayloadCapturesWhileErrorUnion from "!!raw-loader!./25.payload-captures-while-error-union.zig";
import PayloadCapturesForCapture from "!!raw-loader!./25.payload-captures-for-capture.zig";
import PayloadCapturesSwitchCapture from "!!raw-loader!./25.payload-captures-switch-capture.zig";
import PayloadCapturesForPointerCapture from "!!raw-loader!./25.payload-captures-for-pointer-capture.zig";
# Payload Captures
Payload captures use the syntax `|value|` and appear in many places, some of
which we've seen already. Wherever they appear, they are used to "capture" the
value from something.
With if statements and optionals.
<CodeBlock language="zig">{PayloadCapturesOptionalIf}</CodeBlock>
With if statements and error unions. The else with the error capture is required
here.
<CodeBlock language="zig">{PayloadCapturesErrorUnionIf}</CodeBlock>
With while loops and optionals. This may have an else block.
<CodeBlock language="zig">{PayloadCapturesWhileOptional}</CodeBlock>
With while loops and error unions. The else with the error capture is required
here.
<CodeBlock language="zig">{PayloadCapturesWhileErrorUnion}</CodeBlock>
For loops.
<CodeBlock language="zig">{PayloadCapturesForCapture}</CodeBlock>
Switch cases on tagged unions.
<CodeBlock language="zig">{PayloadCapturesSwitchCapture}</CodeBlock>
As we saw in the Union and Optional sections above, values captured with the
`|val|` syntax are immutable (similar to function arguments), but we can use
pointer capture to modify the original values. This captures the values as
pointers that are themselves still immutable, but because the value is now a
pointer, we can modify the original value by dereferencing it:
<CodeBlock language="zig">{PayloadCapturesForPointerCapture}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/16.struct-declarations.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
const Stuff = struct {
x: i32,
y: i32,
fn swap(self: *Stuff) void {
const tmp = self.x;
self.x = self.y;
self.y = tmp;
}
};
test "automatic dereference" {
var thing = Stuff{ .x = 10, .y = 20 };
thing.swap();
try expect(thing.x == 20);
try expect(thing.y == 10);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/18.integer-safe-overflow.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "well defined overflow" {
var a: u8 = 255;
a +%= 1;
try expect(a == 0);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.error-payload-capture.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn failingFunction() error{Oops}!void {
return error.Oops;
}
test "returning an error" {
failingFunction() catch |err| {
try expect(err == error.Oops);
return;
};
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/15.enum-ordinal-override.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
const Value2 = enum(u32) {
hundred = 100,
thousand = 1000,
million = 1000000,
next,
};
test "set enum ordinal value" {
try expect(@intFromEnum(Value2.hundred) == 100);
try expect(@intFromEnum(Value2.thousand) == 1000);
try expect(@intFromEnum(Value2.million) == 1000000);
try expect(@intFromEnum(Value2.next) == 1000001);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.error-union.zig | // hide-start
const expect = @import("std").testing.expect;
const FileOpenError = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error{OutOfMemory};
// hide-end
test "error union" {
const maybe_error: AllocationError!u16 = 10;
const no_error = maybe_error catch 0;
try expect(@TypeOf(no_error) == u16);
try expect(no_error == 10);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/04.while.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while" {
var i: u8 = 2;
while (i < 100) {
i *= 2;
}
try expect(i == 128);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/15.enum-ordinal.zig | // hide-start
const expect = @import("std").testing.expect;
const Value = enum(u2) { zero, one, two };
// hide-end
test "enum ordinal value" {
try expect(@intFromEnum(Value.zero) == 0);
try expect(@intFromEnum(Value.one) == 1);
try expect(@intFromEnum(Value.two) == 2);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/29.sentinel-termination-coercion.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "coercion" {
const a: [*:0]u8 = undefined;
const b: [*]u8 = a;
const c: [5:0]u8 = undefined;
const d: [5]u8 = c;
const e: [:0]f32 = undefined;
const f: []f32 = e;
_ = .{ b, d, f }; //ignore unused
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/02-arrays.md | # Arrays
Arrays are denoted by `[N]T`, where `N` is the number of elements in the array
and `T` is the type of those elements (i.e., the array's child type).
For array literals, `N` may be replaced by `_` to infer the size of the array.
```zig
const a = [5]u8{ 'h', 'e', 'l', 'l', 'o' };
const b = [_]u8{ 'w', 'o', 'r', 'l', 'd' };
```
To get the size of an array, simply access the array's `len` field.
```zig
const array = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
const length = array.len; // 5
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/19.floats-widening.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "float widening" {
const a: f16 = 0;
const b: f32 = a;
const c: f128 = b;
try expect(c == @as(f128, a));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/06.functions-recursion.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn fibonacci(n: u16) u16 {
if (n == 0 or n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
test "function recursion" {
const x = fibonacci(10);
try expect(x == 55);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/17-unions.mdx | import CodeBlock from "@theme/CodeBlock";
import TaggedUnion from "!!raw-loader!./17.union-tagged.zig";
# Unions
Zig's unions allow you to define types that store one value of many possible
typed fields; only one field may be active at one time.
Bare union types do not have a guaranteed memory layout. Because of this, bare
unions cannot be used to reinterpret memory. Accessing a field in a union that
is not active is detectable illegal behaviour.
```zig
const Result = union {
int: i64,
float: f64,
bool: bool,
};
test "simple union" {
var result = Result{ .int = 1234 };
result.float = 12.34;
}
```
```
test "simple union"...access of inactive union field
.\tests.zig:342:12: 0x7ff62c89244a in test "simple union" (test.obj)
result.float = 12.34;
^
```
Tagged unions are unions that use an enum to detect which field is active. Here
we make use of payload capturing again, to switch on the tag type of a union
while also capturing the value it contains. Here we use a _pointer capture_;
captured values are immutable, but with the `|*value|` syntax, we can capture a
pointer to the values instead of the values themselves. This allows us to use
dereferencing to mutate the original value.
<CodeBlock language="zig">{TaggedUnion}</CodeBlock>
The tag type of a tagged union can also be inferred. This is equivalent to the
Tagged type above.
```zig
const Tagged = union(enum) { a: u8, b: f32, c: bool };
```
`void` member types can have their type omitted from the syntax. Here, none is
of type `void`.
```zig
const Tagged2 = union(enum) { a: u8, b: f32, c: bool, none };
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/01-assignment.mdx | ---
pagination_prev: getting-started/running-tests
---
import CodeBlock from "@theme/CodeBlock";
import Assignment from "!!raw-loader!./01.assignment.zig";
import Undefined from "!!raw-loader!./01.undefined.zig";
# Assignment
Value assignment has the following syntax:
`(const|var) identifier[: type] = value`.
- `const` indicates that `identifier` is a **constant** that stores an immutable
value.
- `var` indicates that `identifier` is a **variable** that stores a mutable
value.
- `: type` is a type annotation for `identifier`, and may be omitted if the data
type of `value` can be inferred.
<CodeBlock language="zig">{Assignment}</CodeBlock>
Constants and variables _must_ have a value. If no known value can be given, the
[`undefined`](https://ziglang.org/documentation/master/#undefined) value, which
coerces to any type, may be used as long as a type annotation is provided.
<CodeBlock language="zig">{Undefined}</CodeBlock>
Where possible, `const` values are preferred over `var` values.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/09.switch-expression.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "switch expression" {
var x: i8 = 10;
x = switch (x) {
-1...1 => -x,
10, 100 => @divExact(x, 10),
else => x,
};
try expect(x == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/23.optionals-orelse.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "orelse" {
const a: ?f32 = null;
const fallback_value: f32 = 0;
const b = a orelse fallback_value;
try expect(b == 0);
try expect(@TypeOf(b) == f32);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/04-while-loops.mdx | import CodeBlock from "@theme/CodeBlock";
import While from "!!raw-loader!./04.while.zig";
import WhileContinueExpression from "!!raw-loader!./04.while-continue-expression.zig";
import WhileContinue from "!!raw-loader!./04.while-continue.zig";
import WhileBreak from "!!raw-loader!./04.while-break.zig";
# While loops
Zig's while loop has three parts - a condition, a block and a continue
expression.
Without a continue expression.
<CodeBlock language="zig">{While}</CodeBlock>
With a continue expression.
<CodeBlock language="zig">{WhileContinueExpression}</CodeBlock>
With a `continue`.
<CodeBlock language="zig">{WhileContinue}</CodeBlock>
With a `break`.
<CodeBlock language="zig">{WhileBreak}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/23.optionals-if-payload.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "if optional payload capture" {
const a: ?i32 = 5;
if (a != null) {
const value = a.?;
_ = value;
}
var b: ?i32 = 5;
if (b) |*value| {
value.* += 1;
}
try expect(b.? == 6);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-for-pointer-capture.zig | // hide-start
const expect = @import("std").testing.expect;
const eql = @import("std").mem.eql;
//hide-end
test "for with pointer capture" {
var data = [_]u8{ 1, 2, 3 };
for (&data) |*byte| byte.* += 1;
try expect(eql(u8, &data, &[_]u8{ 2, 3, 4 }));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/29-sentinel-termination.mdx | import CodeBlock from "@theme/CodeBlock";
import SentinelTerminationPtrcast from "!!raw-loader!./29.sentinel-termination-ptrcast.zig";
import SentinelTerminationStringLiteral from "!!raw-loader!./29.sentinel-termination-string-literal.zig";
import SentinelTerminationCString from "!!raw-loader!./29.sentinel-termination-c-string.zig";
import SentinelTerminationCoercion from "!!raw-loader!./29.sentinel-termination-coercion.zig";
import SentinelTerminationSlicing from "!!raw-loader!./29.sentinel-termination-slicing.zig";
# Sentinel Termination
Arrays, slices and many pointers may be terminated by a value of their child
type. This is known as sentinel termination. These follow the syntax `[N:t]T`,
`[:t]T`, and `[*:t]T`, where `t` is a value of the child type `T`.
An example of a sentinel terminated array. The built-in
[`@ptrCast`](https://ziglang.org/documentation/master/#ptrCast) is used to
perform an unsafe type conversion. This shows us that the last element of the
array is followed by a 0 byte.
<CodeBlock language="zig">{SentinelTerminationPtrcast}</CodeBlock>
The types of string literals is `*const [N:0]u8`, where N is the length of the
string. This allows string literals to coerce to sentinel terminated slices, and
sentinel terminated many pointers. Note: string literals are UTF-8 encoded.
<CodeBlock language="zig">{SentinelTerminationStringLiteral}</CodeBlock>
`[*:0]u8` and `[*:0]const u8` perfectly model C's strings.
<CodeBlock language="zig">{SentinelTerminationCString}</CodeBlock>
Sentinel terminated types coerce to their non-sentinel-terminated counterparts.
<CodeBlock language="zig">{SentinelTerminationCoercion}</CodeBlock>
Sentinel terminated slicing is provided which can be used to create a sentinel
terminated slice with the syntax `x[n..m:t]`, where `t` is the terminator value.
Doing this is an assertion from the programmer that the memory is terminated
where it should be - getting this wrong is detectable illegal behaviour.
<CodeBlock language="zig">{SentinelTerminationSlicing}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/23.optionals-while-capture.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
var numbers_left: u32 = 4;
fn eventuallyNullSequence() ?u32 {
if (numbers_left == 0) return null;
numbers_left -= 1;
return numbers_left;
}
test "while null capture" {
var sum: u32 = 0;
while (eventuallyNullSequence()) |value| {
sum += value;
}
try expect(sum == 6); // 3 + 2 + 1
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-for-capture.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "for capture" {
const x = [_]i8{ 1, 5, 120, -5 };
for (x) |v| try expect(@TypeOf(v) == i8);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/06-functions.mdx | import CodeBlock from "@theme/CodeBlock";
import Functions from "!!raw-loader!./06.functions.zig";
import FunctionsRecursion from "!!raw-loader!./06.functions-recursion.zig";
# Functions
**All function arguments are immutable** - if a copy is desired the user must
explicitly make one. Unlike variables, which are snake_case, functions are
camelCase. Here's an example of declaring and calling a simple function.
<CodeBlock language="zig">{Functions}</CodeBlock>
Recursion is allowed:
<CodeBlock language="zig">{FunctionsRecursion}</CodeBlock>
When recursion happens, the compiler is no longer able to work out the maximum
stack size, which may result in unsafe behaviour - a stack overflow. Details on
how to achieve safe recursion will be covered in future.
Values can be ignored using `_` instead of a variable or const declaration. This
does not work at the global scope (i.e. it only works inside functions and
blocks) and is useful for ignoring the values returned from functions if you do
not need them.
```zig
_ = 10;
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.error-set-coercion.zig | // hide-start
const expect = @import("std").testing.expect;
const FileOpenError = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
// hide-end
const AllocationError = error{OutOfMemory};
test "coerce error from a subset to a superset" {
const err: FileOpenError = AllocationError.OutOfMemory;
try expect(err == FileOpenError.OutOfMemory);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/14.slices-2.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "slices 2" {
const array = [_]u8{ 1, 2, 3, 4, 5 };
const slice = array[0..3];
try expect(@TypeOf(slice) == *const [3]u8);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.errdefer.zig | // hide-start
const expect = @import("std").testing.expect;
fn failingFunction() error{Oops}!void {
return error.Oops;
}
//hide-end
var problems: u32 = 98;
fn failFnCounter() error{Oops}!void {
errdefer problems += 1;
try failingFunction();
}
test "errdefer" {
failFnCounter() catch |err| {
try expect(err == error.Oops);
try expect(problems == 99);
return;
};
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-type.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
fn GetBiggerInt(comptime T: type) type {
return @Type(.{
.Int = .{
.bits = @typeInfo(T).Int.bits + 1,
.signedness = @typeInfo(T).Int.signedness,
},
});
}
test "@Type" {
try expect(GetBiggerInt(u8) == u9);
try expect(GetBiggerInt(i31) == i32);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-anytype.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
fn plusOne(x: anytype) @TypeOf(x) {
return x + 1;
}
test "inferred function parameter" {
try expect(plusOne(@as(u32, 1)) == 2);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/28-anonymous-structs.mdx | import CodeBlock from "@theme/CodeBlock";
import AnonymousStructsLiteral from "!!raw-loader!./28.anonymous-structs-literal.zig";
import AnonymousStructsFullyAnonymous from "!!raw-loader!./28.anonymous-structs-fully-anonymous.zig";
import AnonymousStructsTuple from "!!raw-loader!./28.anonymous-structs-tuple.zig";
# Anonymous Structs
The struct type may be omitted from a struct literal. These literals may coerce
to other struct types.
<CodeBlock language="zig">{AnonymousStructsLiteral}</CodeBlock>
Anonymous structs may be completely anonymous i.e. without being coerced to
another struct type.
<CodeBlock language="zig">{AnonymousStructsFullyAnonymous}</CodeBlock>
{/* TODO: mention tuple slicing when it's implemented */}
Anonymous structs without field names may be created and are referred to as
**tuples**. These have many of the properties that arrays do; tuples can be
iterated over, indexed, can be used with the `++` and `**` operators, and have a
len field. Internally, these have numbered field names starting at `"0"`, which
may be accessed with the special syntax `@"0"` which acts as an escape for the
syntax - things inside `@""` are always recognised as identifiers.
An `inline` loop must be used to iterate over the tuple here, as the type of
each tuple field may differ.
<CodeBlock language="zig">{AnonymousStructsTuple}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-type-branching.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "branching on types" {
const a = 5;
const b: if (a < 10) f32 else i32 = 5;
try expect(b == 5);
try expect(@TypeOf(b) == f32);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/01.assignment.zig | const constant: i32 = 5; // signed 32-bit constant
var variable: u32 = 5000; // unsigned 32-bit variable
// @as performs an explicit type coercion
const inferred_constant = @as(i32, 5);
var inferred_variable = @as(u32, 5000);
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/28.anonymous-structs-literal.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "anonymous struct literal" {
const Point = struct { x: i32, y: i32 };
const pt: Point = .{
.x = 13,
.y = 67,
};
try expect(pt.x == 13);
try expect(pt.y == 67);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/28.anonymous-structs-tuple.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "tuple" {
const values = .{
@as(u32, 1234),
@as(f64, 12.34),
true,
"hi",
} ++ .{false} ** 2;
try expect(values[0] == 1234);
try expect(values[4] == false);
inline for (values, 0..) |v, i| {
if (i != 2) continue;
try expect(v);
}
try expect(values.len == 6);
try expect(values.@"3"[0] == 'h');
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/20-labelled-blocks.md | # Labelled Blocks
Blocks in Zig are expressions and can be given labels, which are used to yield
values. Here, we are using a label called `blk`. Blocks yield values, meaning
they can be used in place of a value. The value of an empty block `{}` is a
value of the type `void`.
```zig
test "labelled blocks" {
const count = blk: {
var sum: u32 = 0;
var i: u32 = 0;
while (i < 10) : (i += 1) sum += i;
break :blk sum;
};
try expect(count == 45);
try expect(@TypeOf(count) == u32);
}
```
This can be seen as being equivalent to C's `i++`.
<!--no_test-->
```zig
blk: {
const tmp = i;
i += 1;
break :blk tmp;
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/22-loops-as-expressions.md | # Loops as Expressions
Like `return`, `break` accepts a value. This can be used to yield a value from a
loop. Loops in Zig also have an `else` branch, which is evaluated when the loop
is not exited with a `break`.
```zig
fn rangeHasNumber(begin: usize, end: usize, number: usize) bool {
var i = begin;
return while (i < end) : (i += 1) {
if (i == number) {
break true;
}
} else false;
}
test "while loop expression" {
try expect(rangeHasNumber(0, 10, 3));
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/04.while-break.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "while with break" {
var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
if (i == 2) break;
sum += i;
}
try expect(sum == 1);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/19.floats-literals.zig | const floating_point: f64 = 123.0E+77;
const another_float: f64 = 123.0;
const yet_another: f64 = 123.0e+77;
const hex_floating_point: f64 = 0x103.70p-5;
const another_hex_float: f64 = 0x103.70;
const yet_another_hex_float: f64 = 0x103.70P-5;
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/12-pointer-sized-integers.md | # Pointer Sized Integers
`usize` and `isize` are given as unsigned and signed integers which are the same
size as pointers.
```zig
test "usize" {
try expect(@sizeOf(usize) == @sizeOf(*u8));
try expect(@sizeOf(isize) == @sizeOf(*u8));
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/09-switch.mdx | import CodeBlock from "@theme/CodeBlock";
import SwitchStatement from "!!raw-loader!./09.switch-statement.zig";
import SwitchExpression from "!!raw-loader!./09.switch-expression.zig";
# Switch
Zig's `switch` works as both a statement and an expression. The types of all
branches must coerce to the type which is being switched upon. All possible
values must have an associated branch - values cannot be left out. Cases cannot
fall through to other branches.
An example of a switch statement. The else is required to satisfy the
exhaustiveness of this switch.
<CodeBlock language="zig">{SwitchStatement}</CodeBlock>
Here is the former, but as a switch expression.
<CodeBlock language="zig">{SwitchExpression}</CodeBlock>
:::info
Now is the perfect time to use what you've learned and [solve a problem together](/posts/fizz-buzz).
:::
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/17.union-tagged.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
const Tag = enum { a, b, c };
const Tagged = union(Tag) { a: u8, b: f32, c: bool };
test "switch on tagged union" {
var value = Tagged{ .b = 1.5 };
switch (value) {
.a => |*byte| byte.* += 1,
.b => |*float| float.* *= 2,
.c => |*b| b.* = !b.*,
}
try expect(value.b == 3);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/25.payload-captures-while-optional.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "while optional" {
var i: ?u32 = 10;
while (i) |num| : (i.? -= 1) {
try expect(@TypeOf(num) == u32);
if (num == 1) {
i = null;
break;
}
}
try expect(i == null);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/30-vectors.mdx | import CodeBlock from "@theme/CodeBlock";
import VectorsAdd from "!!raw-loader!./30.vectors-add.zig";
import VectorsIndexing from "!!raw-loader!./30.vectors-indexing.zig";
import VectorsSplatScalar from "!!raw-loader!./30.vectors-splat-scalar.zig";
import VectorsLooping from "!!raw-loader!./30.vectors-looping.zig";
import VectorsCoercion from "!!raw-loader!./30.vectors-coercion.zig";
# Vectors
Zig provides vector types for SIMD. These are not to be conflated with vectors
in a mathematical sense, or vectors like C++'s std::vector (for this, see
"Arraylist" in chapter 2). Vectors may be created using the
[`@Type`](https://ziglang.org/documentation/master/#Type) built-in we used
earlier, and
[`std.meta.Vector`](https://ziglang.org/documentation/master/std/#std;meta.Vector)
provides a shorthand for this.
Vectors can only have child types of booleans, integers, floats and pointers.
Operations between vectors with the same child type and length can take place.
These operations are performed on each of the values in the
vector.[`std.meta.eql`](https://ziglang.org/documentation/master/std/#std;meta.eql)
is used here to check for equality between two vectors (also useful for other
types like structs).
<CodeBlock language="zig">{VectorsAdd}</CodeBlock>
Vectors are indexable.
<CodeBlock language="zig">{VectorsIndexing}</CodeBlock>
The built-in function
[`@splat`](https://ziglang.org/documentation/master/#splat) may be used to
construct a vector where all of the values are the same. Here we use it to
multiply a vector by a scalar.
<CodeBlock language="zig">{VectorsSplatScalar}</CodeBlock>
Vectors do not have a `len` field like arrays, but may still be looped over.
<CodeBlock language="zig">{VectorsLooping}</CodeBlock>
```zig
test "vector looping" {
const x = @Vector(4, u8){ 255, 0, 255, 0 };
var sum = blk: {
var tmp: u10 = 0;
var i: u8 = 0;
while (i < 4) : (i += 1) tmp += x[i];
break :blk tmp;
};
try expect(sum == 510);
}
```
Vectors coerce to their respective arrays.
<CodeBlock language="zig">{VectorsCoercion}</CodeBlock>
It is worth noting that using explicit vectors may result in slower software if
you do not make the right decisions - the compiler's auto-vectorisation is
fairly smart as-is.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/29.sentinel-termination-slicing.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "sentinel terminated slicing" {
var x = [_:0]u8{255} ** 3;
const y = x[0..3 :0];
_ = y;
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/26-inline-loops.md | # Inline Loops
`inline` loops are unrolled, and allow some things to happen that only work at
compile time. Here we use a
[`for`](https://ziglang.org/documentation/master/#inline-for), but a
[`while`](https://ziglang.org/documentation/master/#inline-while) works
similarly.
```zig
test "inline for" {
const types = [_]type{ i32, f32, u8, bool };
var sum: usize = 0;
inline for (types) |T| sum += @sizeOf(T);
try expect(sum == 10);
}
```
Using these for performance reasons is inadvisable unless you've tested that
explicitly unrolling is faster; the compiler tends to make better decisions here
than you.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/07.defer-multi.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
test "multi defer" {
var x: f32 = 5;
{
defer x += 2;
defer x /= 2;
}
try expect(x == 4.5);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/10.switch-unreachable.zig | // hide-start
const expect = @import("std").testing.expect;
// hide-end
fn asciiToUpper(x: u8) u8 {
return switch (x) {
'a'...'z' => x + 'A' - 'a',
'A'...'Z' => x,
else => unreachable,
};
}
test "unreachable switch" {
try expect(asciiToUpper('a') == 'A');
try expect(asciiToUpper('A') == 'A');
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/10-runtime-safety.mdx | import CodeBlock from "@theme/CodeBlock";
import SwitchUnreachable from "!!raw-loader!./10.switch-unreachable.zig";
# Runtime Safety
Zig provides a level of safety, where problems may be found during execution.
Safety can be left on, or turned off. Zig has many cases of so-called
**detectable illegal behaviour**, meaning that illegal behaviour will be caught
(causing a panic) with safety on, but will result in undefined behaviour with
safety off. Users are strongly recommended to develop and test their software
with safety on, despite its speed penalties.
For example, runtime safety protects you from out of bounds indices.
```zig
test "out of bounds" {
const a = [3]u8{ 1, 2, 3 };
var index: u8 = 5;
const b = a[index];
_ = b;
_ = &index;
}
```
```
test "out of bounds"...index out of bounds
.\tests.zig:43:14: 0x7ff698cc1b82 in test "out of bounds" (test.obj)
const b = a[index];
^
```
The user may disable runtime safety for the current block using the built-in
function
[`@setRuntimeSafety`](https://ziglang.org/documentation/master/#setRuntimeSafety).
```zig
test "out of bounds, no safety" {
@setRuntimeSafety(false);
const a = [3]u8{ 1, 2, 3 };
var index: u8 = 5;
const b = a[index];
_ = b;
_ = &index;
}
```
Safety is off for some build modes (to be discussed later).
# Unreachable
[`unreachable`](https://ziglang.org/documentation/master/#unreachable) is an
assertion to the compiler that this statement will not be reached. It can tell
the compiler that a branch is impossible, which the optimiser can then take
advantage of. Reaching an
[`unreachable`](https://ziglang.org/documentation/master/#unreachable) is
detectable illegal behaviour.
As it is of the type
[`noreturn`](https://ziglang.org/documentation/master/#noreturn), it is
compatible with all other types. Here it coerces to u32.
```zig
test "unreachable" {
const x: i32 = 1;
const y: u32 = if (x == 2) 5 else unreachable;
_ = y;
}
```
```
test "unreachable"...reached unreachable code
.\tests.zig:211:39: 0x7ff7e29b2049 in test "unreachable" (test.obj)
const y: u32 = if (x == 2) 5 else unreachable;
^
```
Here is an unreachable being used in a switch.
<CodeBlock language="zig">{SwitchUnreachable}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/29.sentinel-termination-c-string.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
test "C string" {
const c_string: [*:0]const u8 = "hello";
var array: [5]u8 = undefined;
var i: usize = 0;
while (c_string[i] != 0) : (i += 1) {
array[i] = c_string[i];
}
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/13-many-item-pointers.md | # Many-item Pointers
Sometimes, you may have a pointer to an unknown number of elements. `[*]T` is
the solution for this, which works like `*T` but also supports indexing syntax,
pointer arithmetic, and slicing. Unlike `*T`, it cannot point to a type that
does not have a known size. `*T` coerces to `[*]T`.
These many pointers may point to any amount of elements, including 0 and 1.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/24.comptime-return-struct.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
fn Vec(
comptime count: comptime_int,
comptime T: type,
) type {
return struct {
data: [count]T,
const Self = @This();
fn abs(self: Self) Self {
var tmp = Self{ .data = undefined };
for (self.data, 0..) |elem, i| {
tmp.data[i] = if (elem < 0)
-elem
else
elem;
}
return tmp;
}
fn init(data: [count]T) Self {
return Self{ .data = data };
}
};
}
const eql = @import("std").mem.eql;
test "generic vector" {
const x = Vec(3, f32).init([_]f32{ 10, -10, 5 });
const y = x.abs();
try expect(eql(f32, &y.data, &[_]f32{ 10, 10, 5 }));
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/11-pointers.mdx | import CodeBlock from "@theme/CodeBlock";
import Pointers from "!!raw-loader!./11.pointers.zig";
# Pointers
Normal pointers in Zig cannot have 0 or null as a value. They follow the syntax
`*T`, where `T` is the child type.
Referencing is done with `&variable`, and dereferencing is done with
`variable.*`.
<CodeBlock language="zig">{Pointers}</CodeBlock>
Trying to set a `*T` to the value 0 is detectable illegal behaviour.
```zig
test "naughty pointer" {
var x: u16 = 0;
var y: *u8 = @ptrFromInt(x);
_ = y;
}
```
```
Test [23/126] test.naughty pointer... thread 21598 panic: cast causes pointer to be null
./test-c1.zig:252:18: 0x260a91 in test.naughty pointer (test)
var y: *u8 = @ptrFromInt(x);
^
```
Zig also has const pointers, which cannot be used to modify the referenced data.
Referencing a const variable will yield a const pointer.
```zig
test "const pointers" {
const x: u8 = 1;
var y = &x;
y.* += 1;
}
```
```
error: cannot assign to constant
y.* += 1;
^
```
A `*T` coerces to a `*const T`.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/08.error-try.zig | // hide-start
const expect = @import("std").testing.expect;
fn failingFunction() error{Oops}!void {
return error.Oops;
}
//hide-end
fn failFn() error{Oops}!i32 {
try failingFunction();
return 12;
}
test "try" {
const v = failFn() catch |err| {
try expect(err == error.Oops);
return;
};
try expect(v == 12); // is never reached
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/01.undefined.zig | const a: i32 = undefined;
var b: u32 = undefined;
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/23-optionals.mdx | import CodeBlock from "@theme/CodeBlock";
import OptionalsFind from "!!raw-loader!./23.optionals-find.zig";
import OptionalsOrelse from "!!raw-loader!./23.optionals-orelse.zig";
import OptionalsOrelseUnreachable from "!!raw-loader!./23.optionals-orelse-unreachable.zig";
import OptionalsIfPayload from "!!raw-loader!./23.optionals-if-payload.zig";
import OptionalsWhileCapture from "!!raw-loader!./23.optionals-while-capture.zig";
# Optionals
Optionals use the syntax `?T` and are used to store the data
[`null`](https://ziglang.org/documentation/master/#null), or a value of type
`T`.
<CodeBlock language="zig">{OptionalsFind}</CodeBlock>
Optionals support the `orelse` expression, which acts when the optional is
[`null`](https://ziglang.org/documentation/master/#null). This unwraps the
optional to its child type.
<CodeBlock language="zig">{OptionalsOrelse}</CodeBlock>
`.?` is a shorthand for `orelse unreachable`. This is used for when you know it
is impossible for an optional value to be null, and using this to unwrap a
[`null`](https://ziglang.org/documentation/master/#null) value is detectable
illegal behaviour.
<CodeBlock language="zig">{OptionalsOrelseUnreachable}</CodeBlock>
Both `if` expressions and `while` loops support taking optional values as conditions,
allowing you to "capture" the inner non-null value.
Here we use an `if` optional payload capture; a and b are equivalent here.
`if (b) |value|` captures the value of `b` (in the cases where `b` is not null),
and makes it available as `value`. As in the union example, the captured value
is immutable, but we can still use a pointer capture to modify the value stored
in `b`.
<CodeBlock language="zig">{OptionalsIfPayload}</CodeBlock>
And with `while`:
<CodeBlock language="zig">{OptionalsWhileCapture}</CodeBlock>
Optional pointer and optional slice types do not take up any extra memory
compared to non-optional ones. This is because internally they use the 0 value
of the pointer for `null`.
This is how null pointers in Zig work - they must be unwrapped to a non-optional
before dereferencing, which stops null pointer dereferences from happening
accidentally.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/15-enums.mdx | import CodeBlock from "@theme/CodeBlock";
import EnumOrdinal from "!!raw-loader!./15.enum-ordinal.zig";
import EnumOrdinalOverride from "!!raw-loader!./15.enum-ordinal-override.zig";
import EnumMethods from "!!raw-loader!./15.enum-methods.zig";
import EnumDeclarations from "!!raw-loader!./15.enum-declarations.zig";
# Enums
Zig's enums allow you to define types with a restricted set of named values.
Let's declare an enum.
```zig
const Direction = enum { north, south, east, west };
```
Enums types may have specified (integer) tag types.
```zig
const Value = enum(u2) { zero, one, two };
```
Enum's ordinal values start at 0. They can be accessed with the built-in
function
[`@intFromEnum`](https://ziglang.org/documentation/master/#intFromEnum).
<CodeBlock language="zig">{EnumOrdinal}</CodeBlock>
Values can be overridden, with the next values continuing from there.
<CodeBlock language="zig">{EnumOrdinalOverride}</CodeBlock>
Enums can be given methods. These act as namespaced functions that can be called
with the dot syntax.
<CodeBlock language="zig">{EnumMethods}</CodeBlock>
Enums can also be given `var` and `const` declarations. These act as namespaced
globals and their values are unrelated and unattached to instances of the enum
type.
<CodeBlock language="zig">{EnumDeclarations}</CodeBlock>
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/01-language-basics/30.vectors-coercion.zig | // hide-start
const expect = @import("std").testing.expect;
//hide-end
const arr: [4]f32 = @Vector(4, f32){ 1, 2, 3, 4 };
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/04-zig-build.mdx | import CodeBlock from "@theme/CodeBlock";
import Build from "!!raw-loader!./04.zig-build-hello/build.zig";
import Hello from "!!raw-loader!./04.zig-build-hello/src/main.zig";
# Zig Build
The `zig build` system allows people to do more advanced things with their Zig
projects, including:
- Pulling in dependencies
- Building multiple artifacts (e.g. building both a static and a dynamic library)
- Providing additional configuration
- Doing custom tasks at build time
- Building with multiple steps (e.g. fetching and processing data before compiling)
The Zig build system allows you to fulfil these more complex use cases, without
bringing in any additional build tools or languages (e.g. cmake, python), all while making good
use of the compiler's in-built caching system.
# Hello Zig Build
Using the Zig build system requires writing some Zig code. Let's create a
directory structure as follows.
```
.
βββ build.zig
βββ src
βββ main.zig
```
Defining a build function as shown below acts as our entry point to the build
system, which will allow us to define a graph of "steps" for the _build runner_
to perform. Place this code into `build.zig`.
<CodeBlock language="zig">{Build}</CodeBlock>
Place your executable's entry point in `src/main.zig`.
<CodeBlock language="zig">{Hello}</CodeBlock>
We can now run `zig build` which will output our executable.
```
$ zig build
$ ./zig-out/bin/hello
Hello, Zig Build!
```
# Target & Optimisation Options
Previously, we've used `zig build-exe` with `-target` and `-O` to tell Zig what
target and optimisation mode to use. When using the Zig build system, these settings are
now passed into `b.addExecutable`.
Most Zig projects will want to use these standard options.
```zig
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
```
When using `standardTargetOptions` and `standardOptimizeOption` your target will
default to native, meaning that the target of the executable will match the
computer that it was built on. The optimisation mode will default to debug.
If you run `zig build --help`, you can see that these functions have registered
project-specific build options.
```
Project-Specific Options:
-Dtarget=[string] The CPU architecture, OS, and ABI to build for
-Dcpu=[string] Target CPU features to add or subtract
-Doptimize=[enum] Prioritize performance, safety, or binary size (-O flag)
Supported Values:
Debug
ReleaseSafe
ReleaseFast
ReleaseSmall
```
We can now supply them via arguments, e.g.
```
zig build -Dtarget=x86_64-windows -Dcpu=x86_64_v3 -Doptimize=ReleaseSafe
```
# Adding an Option
Thanks to the standard target and optimise options, we already have some useful
build options. In more advanced projects, you may want to add your own
project-specific options; here is a basic example of creating and using an option
that changes the executable's name.
```zig
const exe_name = b.option(
[]const u8,
"exe_name",
"Name of the executable",
) orelse "hello";
const exe = b.addExecutable(.{
.name = exe_name,
.root_source_file = .{ .path = "src/main.zig" },
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
```
If you now run `zig build --help`, we can see that the project-specific build
options have been expanded to include `exe_name`.
```
Project-Specific Options:
-Dexe_name=[string] Name of the executable
-Dtarget=[string] The CPU architecture, OS, and ABI to build for
```
```
$ zig build -Dtarget=x86_64-windows -Dexe_name="Hello!"
$ file zig-out/bin/Hello\!.exe
zig-out/bin/Hello!.exe: PE32+ executable (console) x86-64, for MS Windows, 7 sections
```
# Adding a Run Step
We've previously used `zig run` as a convenient shortcut for calling `zig build-exe`
and then running the resulting binary. We can quite easily do something similar
using the Zig build system.
```zig
b.installArtifact(exe);
const run_exe = b.addRunArtifact(exe);
const run_step = b.step("run", "Run the application");
run_step.dependOn(&run_exe.step);
```
```
$ zig build run
Hello, Zig Build!
```
The Zig build system uses a DAG (directed acyclic graph) of steps that it runs
concurrently. Here we've created a step called "run", which depends on the
`run_exe` step, which depends on our compile step.
Let's have a look at the breakdown of steps in our build.
```
$ zig build run --summary all
Hello, Zig Build!
Build Summary: 3/3 steps succeeded
run success
ββ run hello success 471us MaxRSS:3M
ββ zig build-exe hello Debug native success 881ms MaxRSS:220M
```
We will see more advanced build graphs as we progress.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/_category_.json | {
"label": "Build System",
"link": {
"description": "Getting started with the Zig programming language."
}
} |
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/06-generating-documentation.md | ---
pagination_next: working-with-c/abi
---
# Generating Documentation
The Zig compiler comes with automatic documentation generation. This can be
invoked by adding `-femit-docs` to your `zig build-{exe, lib, obj}` or `zig run`
command. This documentation is saved into `./docs`, as a small static website.
Zig's documentation generation makes use of _doc comments_ which are similar to
comments, using `///` instead of `//`, and preceding globals.
Here we will save this as `x.zig` and build documentation for it with
`zig build-lib -femit-docs x.zig -target native-windows`. There are some things
to take away here:
- Only things that are public with a doc comment will appear
- Blank doc comments may be used
- Doc comments can make use of subset of markdown
- Things will only appear inside generated documentation if the compiler
analyses them; you may need to force analysis to happen to get things to
appear.
<!--no_test-->
```zig
const std = @import("std");
const w = std.os.windows;
///**Opens a process**, giving you a handle to it.
///[MSDN](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess)
pub extern "kernel32" fn OpenProcess(
///[The desired process access rights](https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights)
dwDesiredAccess: w.DWORD,
///
bInheritHandle: w.BOOL,
dwProcessId: w.DWORD,
) callconv(w.WINAPI) ?w.HANDLE;
///spreadsheet position
pub const Pos = struct{
///row
x: u32,
///column
y: u32,
};
pub const message = "hello!";
//used to force analysis, as these things aren't otherwise referenced.
comptime {
_ = OpenProcess;
_ = Pos;
_ = message;
}
//Alternate method to force analysis of everything automatically, but only in a test build:
test "Force analysis" {
comptime {
std.testing.refAllDecls(@This());
}
}
```
When using a `build.zig` this may be invoked by setting the `emit_docs` field to
`.emit` on a `CompileStep`. We can create a build step to generate docs as
follows and invoke it with `$ zig build docs`.
<!--no_test-->
```zig
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const lib = b.addStaticLibrary("x", "src/x.zig");
lib.setBuildMode(mode);
lib.install();
const tests = b.addTest("src/x.zig");
tests.setBuildMode(mode);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&tests.step);
//Build step to generate docs:
const docs = b.addTest("src/x.zig");
docs.setBuildMode(mode);
docs.emit_docs = .emit;
const docs_step = b.step("docs", "Generate docs");
docs_step.dependOn(&docs.step);
}
```
This generation is experimental and often fails with complex examples. This is
used by the
[standard library documentation](https://ziglang.org/documentation/master/std/).
When merging error sets, the left-most error set's documentation strings take
priority over the right. In this case, the doc comment for `C.PathNotFound` is
the doc comment provided in `A`.
<!--no_test-->
```zig
const A = error{
NotDir,
/// A doc comment
PathNotFound,
};
const B = error{
OutOfMemory,
/// B doc comment
PathNotFound,
};
const C = A || B;
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/03-cross-compilation.md | # Cross-compilation
By default, Zig will compile for your combination of CPU and OS. This can be
overridden by `-target`. Let's compile our tiny hello world to a 64-bit arm
Linux platform.
`zig build-exe .\tiny-hello.zig -O ReleaseSmall -fstrip -fsingle-threaded -target aarch64-linux`
[QEMU](https://www.qemu.org/) or similar may be used to conveniently test
executables made for foreign platforms.
Some CPU architectures that you can cross-compile for:
- `x86_64`
- `arm`
- `aarch64`
- `i386`
- `riscv64`
- `wasm32`
Some operating systems you can cross-compile for:
- `linux`
- `macos`
- `windows`
- `freebsd`
- `netbsd`
- `dragonfly`
- `UEFI`
Many other targets are available for compilation but aren't as well tested as
of now. See
[Zig's support table](https://ziglang.org/learn/overview/#wide-range-of-targets-supported)
for more information; the list of well-tested targets is slowly expanding.
As Zig compiles for your specific CPU by default, these binaries may not run on
other computers with slightly different CPU architectures. It may be useful to
instead specify a specific baseline CPU model for greater compatibility. Note:
Choosing an older CPU architecture will bring greater compatibility, but means
you also miss out on newer CPU instructions; there is an efficiency/speed versus
compatibility trade-off here.
Let's compile a binary for a sandybridge CPU (Intel x86_64, circa 2011), so we
can be reasonably sure that someone with an x86_64 CPU can run our binary. Here
we can use `native` in place of our CPU or OS, to use our system's.
`zig build-exe tiny-hello.zig -target x86_64-native -mcpu sandybridge`
Details on what architectures, OSes, CPUs, and ABIs (details on ABIs in the next
chapter) are available can be found by running `zig targets`. Note: the output
is long, and you may want to pipe it to a file, e.g.
`zig targets > targets.json`.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/02-emitting-an-executable.md | # Emitting an Executable
The commands `zig build-exe`, `zig build-lib`, and `zig build-obj` can be used
to output executables, libraries, and objects, respectively. These commands take
in a source file and arguments.
Some common arguments:
- `-fsingle-threaded`, which asserts the binary is single-threaded. This will
turn thread-safety measures such as mutexes into no-ops.
- `-fstrip`, which removes debug info from the binary.
- `--dynamic`, which is used in conjunction with `zig build-lib` to output a
dynamic/shared library.
Let's create a tiny hello world. Save this as `tiny-hello.zig`, and run
`zig build-exe tiny-hello.zig -O ReleaseSmall -fstrip -fsingle-threaded`.
```zig
const std = @import("std");
pub fn main() void {
std.io.getStdOut().writeAll(
"Hello World!",
) catch unreachable;
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/01-build-modes.md | ---
pagination_prev: standard-library/advanced-formatting
---
# Build Modes
Zig provides four build modes, with debug being the default as it produces the
shortest compile times.
| | Runtime Safety | Optimizations |
| ------------ | -------------- | ------------- |
| Debug | Yes | No |
| ReleaseSafe | Yes | Yes, Speed |
| ReleaseSmall | No | Yes, Size |
| ReleaseFast | No | Yes, Speed |
These may be used with `zig run` and `zig test` with the arguments
`-O ReleaseSafe`, `-O ReleaseSmall`, and `-O ReleaseFast`.
Users are recommended to develop their software with runtime safety enabled,
despite its small speed disadvantage.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/04.zig-build-hello/build.zig | const std = @import("std");
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{
.name = "hello",
.root_source_file = .{ .path = "src/main.zig" },
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
b.installArtifact(exe);
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/04.zig-build-hello | repos/zig.guide/website/versioned_docs/version-0.13/03-build-system/04.zig-build-hello/src/main.zig | const std = @import("std");
pub fn main() void {
std.debug.print("Hello, {s}!\n", .{"Zig Build"});
}
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/02-c-primitive-types.md | # C Primitive Types
Zig provides special `c_` prefixed types for conforming to the C ABI. These do
not have fixed sizes but rather change in size depending on the ABI being used.
| Type | C Equivalent | Minimum Size (bits) |
| ------------ | ------------------ | ------------------- |
| c_short | short | 16 |
| c_ushort | unsigned short | 16 |
| c_int | int | 16 |
| c_uint | unsigned int | 16 |
| c_long | long | 32 |
| c_ulong | unsigned long | 32 |
| c_longlong | long long | 64 |
| c_ulonglong | unsigned long long | 64 |
| c_longdouble | long double | N/A |
| anyopaque | void | N/A |
Note: C's void (and Zig's `anyopaque`) has an unknown non-zero size. Zig's
`void` is a true zero-sized type.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/03-calling-conventions.md | # Calling conventions
Calling conventions describe how functions are called. This includes how
arguments are supplied to the function (i.e. where they go - in registers or on
the stack, and how), and how the return value is received.
In Zig, the attribute `callconv` may be given to a function. The calling
conventions available may be found in
[std.builtin.CallingConvention](https://ziglang.org/documentation/master/std/#std.builtin.CallingConvention).
Here we make use of the cdecl calling convention.
```zig
fn add(a: u32, b: u32) callconv(.C) u32 {
return a + b;
}
```
Marking your functions with the C calling convention is crucial when you're
calling Zig from C.
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/06-packed-structs.md | # Packed Structs
By default, all struct fields in Zig are naturally aligned to that of
[`@alignOf(FieldType)`](https://ziglang.org/documentation/master/#alignOf) (the
ABI size), but without a defined layout. Sometimes you may want to have struct
fields with a defined layout that do not conform to your C ABI. `packed` structs
allow you to have extremely precise control of your struct fields, allowing you
to place your fields on a bit-by-bit basis.
Inside packed structs, Zig's integers take their bit-width in space (i.e. a
`u12` has an [`@bitSizeOf`](https://ziglang.org/documentation/master/#bitSizeOf)
of 12, meaning it will take up 12 bits in the packed struct). Bools also take up
1 bit, meaning you can implement bit flags easily.
```zig
const MovementState = packed struct {
running: bool,
crouching: bool,
jumping: bool,
in_air: bool,
};
test "packed struct size" {
try expect(@sizeOf(MovementState) == 1);
try expect(@bitSizeOf(MovementState) == 4);
const state = MovementState{
.running = true,
.crouching = true,
.jumping = true,
.in_air = true,
};
_ = state;
}
```
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/12-zig-cc.md | ---
pagination_next: async/introduction
---
# Zig cc, Zig c++
The Zig executable comes with Clang embedded inside it alongside libraries and
headers required to cross-compile for other operating systems and architectures.
This means that not only can `zig cc` and `zig c++` compile C and C++ code (with
Clang-compatible arguments), but it can also do so while respecting Zig's target
triple argument; the single Zig binary that you have installed has the power to
compile for several different targets without the need to install multiple
versions of the compiler or any addons. Using `zig cc` and `zig c++` also makes
use of Zig's caching system to speed up your workflow.
Using Zig, one can easily construct a cross-compiling toolchain for languages
that use a C and/or C++ compiler.
Some examples in the wild:
- [Using zig cc to cross compile LuaJIT to aarch64-linux from x86_64-linux](https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html)
- [Using zig cc and zig c++ in combination with cgo to cross compile hugo from aarch64-macos to x86_64-linux, with full static linking](https://twitter.com/croloris/status/1349861344330330114)
|
0 | repos/zig.guide/website/versioned_docs/version-0.13 | repos/zig.guide/website/versioned_docs/version-0.13/04-working-with-c/_category_.json | {
"label": "Working with C",
"link": {
"description": "Zig has been designed from the ground up with C interop as a first-class feature. In this section, we will go over how this works."
}
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.