I don't understand how to use this function

/// Returns an owned slice of this string

pub fn toOwned(self: String) Error!?[]u8 {
        if (self.len() != 0) {
            const string = self.str();
            if (self.allocator.alloc(u8, string.len)) |newStr| {
                std.mem.copy(u8, newStr, string);
                return newStr;
            } else |_| {
                return Error.OutOfMemory;
            }
        }

        return null;
    }

How to know if it is an error or null or a varu8

I stumble, over it

please thank you

I understand that we can do this

var varsp  = myStr.toOwned() catch |Error|label: {
                        std.debug.print("unable toOwned: {}\n", .{Error});
                        break :label continue; // or return 
                        };

I think you have to test

if (varsp != null) {  ......
else {....

or do

var varsp  = myStr.toOwned() catch unreachable;

is this the right solution

try and catch are for errors, while if/else and orelse are for optionals. Here are some examples using your code as a starting point.

    var optional_str_1: ?[]u8 = my_str.toOwned() catch |err| {
        std.debug.print("toOwned err={}\n", .{err});
        return;
    };    

    var optional_str_2: ?[]u8 = my_str.toOwned() catch |err| blk: {
        std.debug.print("toOwned err={}\n", .{err});
        break :blk null;
    };    

    if (optional_str_1) |str1| {
        std.debug.print("str1={s}\n", .{str1});
    }

    var str2: []u8 = optional_str_2 orelse "";
    std.debug.print("str2={s}\n", .{str2});
1 Like

Or if you don’t need to print the error, it is much simpler to create optional_str_2:

    var optional_str_2: ?[]u8 = my_str.toOwned() catch null;
1 Like

@jpl Did this answer your question?

1 Like

Yes completely :wink:

1 Like