Open ndrean opened 1 month ago
const std = @import("std");
// the input is a pointer to CONSTANT values; this is valid
fn sum(input: []const u8) u8 {
var sum: u8 = 0;
for (input) |e| sum += e;
return sum;
}
// we add the index to each element of the array
// the argument is a MUTABLE slice
fn mut(input: []u8) []u8 {
// this is not possible: "error: cannot assign to constant"
// for (input, 0..) |e: u8, i: usize| {
// e += i;
// }
// instead, this is valid
for (input, 0..) |_, i: usize| {
input[i] += 1;
}
// alternative
for (input, 0..) |*v: **u8, i: usize| {
v.* += i;
}
return input;
}
test "arrays" {
const cst_input = [_]u8{ 1, 2, 3, 4, 5 };
const sum = sum1(&cst_input);
try std.testing.expectEqual(sum, 15);
// we define a mutable array.
var var_input = [_]u8{ 1, 2, 3, 4, 5 };
// const mutInput = mut(&cst_input); <- this fails
const mutInput = mut(&var_input);
try std.testing.expectEqualSlices(u8, mutInput, &[_]u8{ 2, 3, 4, 5, 6 });
}
This is similar to when you want to mutate data via its pointer (more involved, yes...)
// mutate via the pointer
fn db_ptr(x: *u8) void {
x.* *= 2;
}
// just return another value
fn db(x: u8) u8 {
return x * 2;
}
test "mut" {
var x: u8 = 1;
db_ptr(&x);
try std.testing.expectEqual(x, 2);
var y: u8 = 1;
y = db(y);
try std.testing.expectEqual(y, 2);
}
https://zig.news/ is a good place to search on ziggy problems.
Explore types with
@TypeOf
[building...]
Vademecum
Run
zig test my_file.zig
:Lets summarise
[n]T
of comptime known length. You can instantiate them:const word = [5]u8{'h', 'e', 'l', 'l', 'o'}
with type[5:0]u8
[]T
of typesT
with runtime known length. They are made of a pointer to the first element of an Array and a length.const slice_word = word[0..]
with type*const [4]u8
const zig = "zig"
has type*const [3:0]u8
Ok, now we test our understanding:
We can use it like this:
Now, can we mutate a literal string? Yes, dereference it!
gives:
Structs
Now consider using a struct. Pointers are needed here when you use functions to modify.
We get:
Now consider a struct that holds internal methods. Again, when the method modifies one of the fields of the struct, you must use a pointer. Note that the inner method uses a reflection.
We get as expected:
Pause
Check this video:
WFT Comptime....
❗ References to keep!
A first link:
Then, a GitHub link: