I can pass a 2D matrix whose rows and columns are not known before hand like:
fn foo(comptime m: u16, comptime n: u16, matrix: [m][n]u16) void {
// perform read-only operations on the matrix
}
But I was wondering whether its possible to avoid using comptime in the function signature. I tried a few things but struggling to get the syntax right.
If it is possible to do this, what would the function signature and call look like? And if its not possible, I’d like to understand why.
I’ve been documenting cases where comptime can be avoided:-
If the number of integers in a list is not known beforehand, the function signature and call could look like:
fn bar(slice: []const i16) void {
for(slice, 0..) |value, i| {
print("The value at index {d} is {d}\n", .{i, value});
}
}
test bar {
const sl1: []const i16 = &.{-6, 7, 1};
const sl2 = &.{1, 4, -6, -2, 9};
var arr1: [10]i16 = .{-10, -20, -30, -40, 50, -60, -70, -80, -90, 100};
var arr2 = [_]i16{10, 20, 30, 40, 50, 60, 70, 80};
bar(sl1);
bar(sl2);
bar(arr1[0..9]);
bar(&arr2);
}
or it could also be:
fn baz(slice: []i16) void {
for(slice, 0..) |value, i| {
print("The value at index {d} is {d}\n", .{i, value});
}
}
test baz {
var arr1: [4]i16 = .{-6, 7, 1, -8};
var arr2 = [_]i16{1, 4, -6, -2, 9, 10};
baz(&arr1);
baz(&arr2);
}
Another example is:
If the number of strings in a list is not known beforehand, the function signature and call could like:
fn foo(strings: []const []const u8) void {
for (strings) |string| {
print("{s}\t", .{string});
}
print("\n", .{});
}
fn bar(strings: [][]const u8) void {
for (strings) |string| {
print("{s}\t", .{string});
}
print("\n", .{});
}
test foo {
{
std.debug.print("array of strings\n", .{});
const array_of_slices = [_][]const u8{
"one",
"two",
"three",
"four",
"five",
};
foo(array_of_slices[0..]);
foo(&array_of_slices);
}
{
std.debug.print("slice of strings\n", .{});
const slice_of_slices: []const []const u8 = &.{
"one",
"two",
"three",
};
foo(slice_of_slices);
foo(slice_of_slices[0..]);
}
}
test bar {
{
std.debug.print("array of strings\n", .{});
var array_of_slices = [_][]const u8{
"one",
"two",
"three",
"four",
};
bar(array_of_slices[0..]);
bar(&array_of_slices);
}
}
const std = @import("std");
const print = std.debug.print;