3 ms·
Yes, arrays are another distinction: - an array [3]u8 - a single item non-nullable pointer *u8 - a single item nullable pointer ?*u8 - a multi-item non-null
by dundarious 5y ago
Yes, arrays are another distinction:
- an array [3]u8
- a single item non-nullable pointer *u8
- a single item nullable pointer ?*u8
- a multi-item non-nullable pointer [*]u8
- a multi-item nullable pointer ?[*]u8
- a slice []u8
Typically your API is just made up of slices and non-nullable single item pointers. Arrays are just the typical backing store for a slice, that you might define in main or for small scratch buffers. Here's a typical example of an OS read (where the fd has been set to non-blocking already):
fn readUpTo32Bytes(fd: std.os.fd_t) ![]u8 {
var array: [32]u8 = undefined;
var data = array[0..]; // slice of entire array
data.len = std.os.read(fd, data) catch |err| switch (err) {
error.WouldBlock => 0,
else => return err,
};
handle(data);
}
fn handle(data: []const u8) void { ... }
If you don't need to handle EAGAIN/error.WouldBlock, then just do `data.len = try std.os.read(fd, data);`
I didn't explain the `!` in the `![]u8` return type, but it's basically saying "an error or a []u8", where it's compile time known what the full set of errors is (in this case every error std.os.read can return, minus WouldBlock).
- dundarious 5y agoReplying to note I mistakenly left in the `![]u8` return type when it's not returning any byte slice. Should be `!void`.