Hello,
I’m passing a list of strings to a function as an argument. I can run individual unit tests like:
test "'fl' is the longest common prefix among the strings" {
var input = [_][]const u8{ "flower", "flow", "flight" };
const got = try longestCommonPrefix(&input);
const want: []const u8 = "fl";
try testing.expectEqualStrings(want, got);
}
test "no common prefix among strings" {
var input = [_][]const u8{ "dog", "racecar", "car" };
const got = try longestCommonPrefix(&input);
const want: []const u8 = "";
try testing.expectEqualStrings(want, got);
}
But when I declare a decltest similar to the unit tests like:
test longestCommonPrefix {
const test_cases = [_]struct {
description: []const u8,
input: [][]const u8,
expected: []const u8,
}{
.{
.description = "'fl' is the longest common prefix among the strings",
.input = [_][]const u8{ "flower", "flow", "flight" },
.expected = "fl",
},
.{
.description = "no common prefix among strings",
.input = [_][]const u8{ "dog", "racecar", "car" },
.expected = "",
},
};
for (test_cases) |tc| {
const got = try longestCommonPrefix(tc.input);
const want = tc.expected;
std.debug.print("{s}\n", .{tc.description});
try testing.expectEqualStrings(want, got);
}
}
I get an error:
array literal requires address-of operator (&) to coerce to slice type '[][]const u8'
.input = [_][]const u8{ "flower", "flow", "flight" },
~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I added &
to the .input
, but it gives a different error:
error: expected type '[][]const u8', found '*const [3][]const u8'
.input = &[_][]const u8{ "flower", "flow", "flight" },
~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
longest_common_prefix.zig:54:14: note: cast discards const qualifier
The implementation is:
const std = @import("std");
const testing = std.testing;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
fn ascending(_: void, lhs: []const u8, rhs: []const u8) bool {
return std.mem.order(u8, lhs, rhs) == .lt;
}
fn longestCommonPrefix(strs: [][]const u8) ![]const u8 {
var result: std.ArrayList(u8) = .init(allocator);
std.mem.sort([]const u8, strs, {}, ascending);
const first = strs[0];
const last = strs[strs.len - 1];
for (0..@min(first.len, last.len)) |i| {
if (first[i] == last[i]) {
try result.append(first[i]);
} else {
break;
}
}
return result.toOwnedSlice();
}
How can I correctly run the decltest against it?