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/more_pointers.zig

62 lines
1.5 KiB

const std = @import("std");
const debug = std.debug;
const testing = std.testing;
// general useful coercions for pointers and slices:
//
// 1. [N]T -> *[N]T using &
// 2. [N]T -> []T using [..] and coercion
// 3. *[N] -> []T using coercion
// 4. []u8 -> [*]u8 using `ptr`
// 5. any -> ?any
// 6. any -> const any
test "basics" {
var a = [5]u8{ 'h', 'e', 'l', 'l', 'o' };
var b: []u8 = a[0..];
var c: [5]u8 = a; // deep copy
a[0] = 'c';
debug.print("{s}, {s}, {s}\n", .{ a, b, c });
}
test "slices and pointers" {
const msg = "hello";
testing.expectEqual(@TypeOf(msg), *const [5:0]u8);
const slice: []const u8 = msg;
testing.expectEqual(@TypeOf(slice), []const u8);
}
test "multi-item pointer vs sentinel-terminated pointer" {
const msg = "hello";
testing.expectEqual(@TypeOf(msg), *const [5:0]u8);
const multi: []const u8 = msg[0..]; // coercion
testing.expectEqual(@TypeOf(multi.ptr), [*]const u8); // the ptr field of a slice is of multi-item pointer type
}
test "print string literal" {
const msg = "hello";
printStringLiteral(msg);
}
// coercion at work again
fn printStringLiteral(s: []const u8) void {
debug.print("s = {s}\n", .{s});
}
test "passing pointers as function arguments" {
var bob = Person{ .beans = 0 };
testing.expectEqual(bob.beans, 0);
giveBeans(&bob);
testing.expectEqual(bob.beans, 20);
}
const Person = struct {
beans: usize,
};
fn giveBeans(p: *Person) void {
p.beans += 10; // works
p.*.beans += 10; // also works
}