我在 Zig 中有以下内容
const std = @import("std");
var messages = [2]*[]u8{undefined, undefined};
pub fn main() !void {
// Allocate some strings
const msg1 = "First message";
const msg2 = "Second message has different length";
const allocator = std.heap.page_allocator;
const msg1_ptr = try allocator.alloc(u8, msg1.len);
defer allocator.free(msg1_ptr);
const msg2_ptr = try allocator.alloc(u8, msg2.len);
defer allocator.free(msg2_ptr);
messages[0] = @as(*[]u8, &msg1_ptr);
messages[1] = @as(*[]u8, &msg2_ptr);
它给出了以下错误
src/main.zig:14:30: error: expected type '*[]u8', found '*const []u8'
messages[0] = @as(*[]u8, &msg1_ptr);
^~~~~~~~~
src/main.zig:14:30: note: cast discards const qualifier
referenced by:
callMain: /usr/local/Cellar/zig/0.13.0/lib/zig/std/start.zig:524:32
callMainWithArgs: /usr/local/Cellar/zig/0.13.0/lib/zig/std/start.zig:482:12
remaining reference traces hidden; use '-freference-trace' to see all reference traces
为了解决这个问题,只需将指针的 const 改为 var 即可
var msg1_ptr = try allocator.alloc(u8, msg1.len);
defer allocator.free(msg1_ptr);
var msg2_ptr = try allocator.alloc(u8, msg2.len);
defer allocator.free(msg2_ptr);
为什么 const 指针不能强制转换为 const 无关的指针,但将其更改为 var 是有效的?是不是因为 const 意味着不可变,而 var 则不然,所以限制较少?这是否意味着 const 指针永远不能被强制转换?