How to cast []const u8 to []u8

I have a struct that has []u8 as a field. In the logic of the project I am working, I have a value of []const u8 that I need to assign to this []u8 field, but not sure how to do this.

Currently getting the error

 error: expected type '[]u8', found '[]const u8'

Is it possible to convert []const u8 to []u8? or maybe create a []u8 from the []const u8

1 Like

If you’re absolutely sure, this slice won’t be accessed to modify the data it points to, you can use @constCast. Else you have to make a copy, using std.mem.Allocator.dupe, and don’t forget to free it.

6 Likes

@constCast is only valid if you’ve taken a const pointer to mutable data! If that’s the case, then don’t const cast the slice in the first place.

If not, use allocator.dupe(u8, str) instead.

4 Likes