Skip to main content

must-return-ref

Suspicious
This rule is enabled as a warning by default.

What This Rule Does

Disallows returning copies of types that store a capacity.

Zig does not have move semantics. Returning a value by value copies it. Returning a copy of a struct's field that records how much memory it has allocated can easily lead to memory leaks.

const std = @import("std");
pub const Foo = struct {
list: std.ArrayList(u32),
pub fn getList(self: *Foo) std.ArrayList(u32) {
return self.list;
}
};

pub fn main() !void {
var foo: Foo = .{
.list = try std.ArrayList(u32).init(std.heap.page_allocator)
};
defer foo.list.deinit();
var list = foo.getList();
try list.append(1); // leaked!
}

Examples

Examples of incorrect code for this rule:

fn foo(self: *Foo) std.ArrayList(u32) {
return self.list;
}

Examples of correct code for this rule:

// pass by reference
fn foo(self: *Foo) *std.ArrayList(u32) {
return &self.list;
}

// new instances are fine
fn foo() ArenaAllocator {
return std.mem.ArenaAllocator.init(std.heap.page_allocator);
}

Configuration

This rule has no configuration.