orhun / personal-blog

The source of my blog ✍🏼
https://blog.orhun.dev
27 stars 3 forks source link

https://blog.orhun.dev/zig-bits-01/ #5

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Orhun's Blog

https://blog.orhun.dev/zig-bits-01/

perillo commented 1 year ago

The last example is incorrect (and undefined behavior), since the slice share the same memory from the array.

miktwon commented 1 year ago

Hi, and thanks for the nice article! It was really easy and fun to read. My main programming language is Go, which uses garbage collection. The next question is about the "Allocating the slice" example. Should I pass an allocator and free the returned value if I rewrite your example with a for loop?

orhun commented 1 year ago

@perillo you're right. I will update the example!

@miktwon yup! I recently learned that Zig convention for allocation is that you typically declare an allocator at another higher-scoped unit of code and then pass the allocator as an argument to the function. Apparently the entire standard library is like this. Any code that requires an allocator accepts an allocator as an argument. This helps make functions that allocate more explicitly clear, and the caller can decide the allocator type.

rofrol commented 1 year ago

Tetralux wrote in https://discord.com/channels/605571803288698900/1068000302583787531

Keep in mind that the number of bytes written is unknown to main, and thus the debug log at the end will print the entire buffer, and not just the actual message part. You could do fn zigBits(slice: []u8) usize though to address that. (Return the number written.)

const std = @import("std");

/// Takes a slice as a parameter and fills it with a message.
fn zigBits(slice: []u8) usize {
    // Create an array literal.
    var message = [_]u8{ 'z', 'i', 'g', 'b', 'i', 't', 's' };

    // Print the array as string.
    std.log.debug("{s}", .{message});

    // Update the slice.
    std.mem.copy(u8, slice, &message);
    return message.len;
}

pub fn main() void {
    // Define the message buffer.
    var message: [9]u8 = undefined;

    // Get the message.
    const len = zigBits(&message);

    // Print the message.
    std.log.debug("{s}", .{message[0..len]});
}