使用GeneralPurposeAllocator#allocator时遇类型不匹配错误求助
问题描述
我编写了如下Zig语言write函数:
pub fn write(this: *This, byte: u8) !void { const gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(gpa.deinit() == .ok); const allocator = gpa.allocator(); if (this.capacity < this.count + 1) { const old = this.capacity; this.capacity = increaseCapacity(old); this.code = allocator.realloc(this.code, this.capacity); } this.code[this.count] = byte; this.count += 1; }
执行如下测试代码时:
test "writes byte to the code" { const chunk: *Chunk = try Chunk.init(testing_allocator); const expected: u8 = 0x1; const added: usize = 1; try chunk.write(expected); const actual = chunk.code[0]; try std.testing.expectEqual(chunk.code.len, CAPACITY_THRESHOLD); try std.testing.expectEqual(chunk.count, added); try std.testing.expect(actual == expected); }
在const allocator = gpa.allocator();处出现错误:
error: expected type '*heap.general_purpose_allocator.GeneralPurposeAllocator(.{ .stack_trace_frames = 10, .enable_memory_limit = false, .safety = true, .thread_safe = true, .MutexType = null, .never_unmap = false, .retain_metadata = false, .verbose_log = false })', found '*const heap.general_purpose_allocator.GeneralPurposeAllocator(.{ .stack_trace_frames = 10, .enable_memory_limit = false, .safety = true, .thread_safe = true, .MutexType = null, .never_unmap = false, .retain_metadata = false, .verbose_log = false })'
错误原因
这个错误的核心原因是**gpa被声明为不可变的const变量**,而GeneralPurposeAllocator的allocator()方法需要接收一个可变指针(*Self),但const变量只能生成*const Self类型的指针,类型不匹配导致编译失败。
具体细节:
- 声明
const gpa = ...后,gpa是只读变量,它的指针类型为*const GeneralPurposeAllocator allocator()方法的签名要求接收器是*GeneralPurposeAllocator(可变指针),因为该方法会修改GPA内部的状态(比如跟踪内存分配记录)- Zig的类型系统严格禁止将
*const类型隐式转换为*类型,因此抛出了类型不匹配的错误
修复方案
将const gpa修改为var gpa,让变量具备可变性:
pub fn write(this: *This, byte: u8) !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(gpa.deinit() == .ok); const allocator = gpa.allocator(); if (this.capacity < this.count + 1) { const old = this.capacity; this.capacity = increaseCapacity(old); this.code = try allocator.realloc(this.code, this.capacity); // 补充try处理realloc的错误返回 } this.code[this.count] = byte; this.count += 1; }
额外注意:allocator.realloc是可能返回错误的函数,需要添加try关键字处理错误,否则会触发另一个编译错误。
内容的提问来源于stack exchange,提问作者Ivan Ivanchuk
相关产品推荐
相关产品推荐

