#Strings

1 messages · Page 1 of 1 (latest)

timid harbor
#

Just trying to do toy exercises to get my head around the language. Any idea why I'm getting error: expected type '[]const u8', found 'error{NoSpaceLeft}' at comptime on line 14, I need to return the argument n as a string in the buffer. Also if anyone can advise on working with strings in general, I'm cobbling this together from Google (the exercise wants a buffer filled for some reason, but it'd be nice to do some elegant concatenation I guess)

const std = @import("std");

pub fn main() !void 
{
    var input: [15]u8 = [_]u8{0} ** 15;
    const ip = convert(&input, 15);
    std.debug.print("{s}", .{ip});
}

pub fn convert(buffer: []u8, n: u32) []const u8 
{
    if (n % 3 == 0 and n % 5 == 0 and n % 7 == 0) 
    {
        try std.fmt.bufPrint(buffer, "{d}", .{ n });
        return buffer;
    }

    if (n % 3 == 0) @memmove(buffer[0..5], "Pling");
    if (n % 5 == 0) @memmove(buffer[5..10], "Plang");
    if (n % 7 == 0) @memmove(buffer[10..], "Plong");

    return buffer;
}
#

Also is passing the address of an array, e.g. &input basically a conversion to slice like doing input[0..]

#

nvm, it's because bufPrint is returning an error union. But still interested to know if this is even remotely idiomatic since there seems to be about 9 million ways to deal with strings

sinful hearth
#

line 14 is 'try' - try is equivalent to catch |e| return e. but the function's return type is []const u8, so it's not able to return an error. that's what the error is from.

#

typically I use an ArrayList or Writer for concatenation

// writer example
var buf: [15]u8 = undefined;
const writer = std.Io.Writer.fixed(&buf);
try writer.writeAll("Pling");
try writer.writeAll("Plang");
try writer.writeAll("Plang");
timid harbor
#

Thanks, is there a method for doing formatted writing with this interface?

sinful hearth
#

and you get the result of a Writer.fixed using writer.buffered()

timid harbor
#

I'm confused about how I should handle the writer.print. try will return the error or void in this case, but if try is successful I want to return the buffer. I also want to return the buffer if it fails to write, presuming it will be empty

pub fn convert(buffer: []u8, n: u32) []const u8 
{
    var writer = std.Io.Writer.fixed(buffer);
    
    if (n % 3 != 0 and n % 5 != 0 and n % 7 != 0) 
    {
        try writer.print("{d}", .{ n }) catch { return buffer; };
        return buffer;
    }

    if (n % 3 == 0) try writer.writeAll("Pling");
    if (n % 5 == 0) try writer.writeAll("Plang");
    if (n % 7 == 0) try writer.writeAll("Plong");

    return buffer;
}
sinful hearth
#

also you can't use try with catch - you either use try or you use catch

timid harbor
#

Yeah, it's for an online thing so I have to obey the function sig alas