#Confusion with const variable passing to non const function

1 messages · Page 1 of 1 (latest)

grand wing
#

I want to copy a string into a new pointer 'word_name'. This variable is not modified, therefore the compiler displays an error that I should use const. However, I cannot pass a const pointer to @memcpy.
What is the solution for this problem, use @constCast or am i missing something?

Thanks for your help 🙂

const name_token = self.scanner.advance_word() orelse return ParsingError.General;
const word_name: []const u8 = try allocator.alloc(u8, name_token.len);
@memcpy(word_name, name_token);
jaunty wing
#

either

const word_name = try allocator.alloc(u8, name_token.len);
@memcpy(word_name, name_token);

or just

const work_name = try allocator.dupe(u8, name_token);
grand wing
#

In this case @memcpy shows an error that I cannot pass a const pointer

#

src/parser.zig:111:17: error: cannot memcpy to constant pointer
@memcpy(word_name, name_token);

jaunty wing
#

that's because you have : []const u8

#

which means that you can't change the bytes in the slice

grand wing
#

Ah I was confused I thought the const refers to the pointer itself. Thanks for clarifying

jaunty wing
#

that's the const word_name part, var word_name would mean you want to be able to change the slice to point to something else