Hello,
I’d like to know how I can pass an array to a function. This question was answered on reddit btw.
I have an array like this:
const routes = [_]Route{
.{ .path = "/home", .handler = homeHandler },
};
and then I’d like to pass it to a function, but what would the function’s argument type look like?
The compiler doesn’t just allow me to use []Route
.
Thanks!
Luis
2
May be this example help you understand
fn pass_array(array: [1]Route) void {
_ = array;
}
fn pass_slice(slice: []Route) void {
_ = slice;
}
fn pass_slice_const(slice: []const Route) void {
_ = slice;
}
pub fn main() !void {
const routes = [_]Route{
.{ .path = "/home", .handler = homeHandler },
};
var routes_var = [_]Route{
.{ .path = "/home", .handler = homeHandler },
};
pass_array(routes);
pass_slice(&routes_var);
pass_slice_const(&routes);
}
4 Likes