-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Guided inference of T in generic function #470
Comments
You can currently do
slightly more verbose, but equivalent. I feel like we get a lot of criticism for having sigils, it seems like adding more might be asking for trouble. |
that works! But I guess it doesnt solve the following for example? |
I see, so it does pattern matching. That's pretty convenient. here's how to do that in zig:
|
fn cmp_pattern(a: []const $T, b: []const T)
fn cmp_var(a: var, b: []const @typeOf(a).child)
fn cmp_explicit(comptime T: type, a: []const T, b: []const T) There is a semantic difference between all of these three. cmp_pattern("abc", "abcd");
// cmp_pattern(a: []const u8, b: []const u8)
cmp_var("abc", "abcd");
// cmp_var(a: &const [3]u8, b: []const [3]u8)
// ERROR: cannot coerce [4]u8 to []const [3]u8.
cmp_var("abc"[0..], "abcd");
// cmp_var(a: []const u8, b: []const u8)
cmp_explicit(u8, "abc", "abcd"); I struggled for a while, and couldn't figure out how provide the caller semantics of the proposed I believe this is actually a missing feature. The current recommended workaround is to explicitly give the type as in |
I made it so that if you pass a |
Ah. So it's either a regression or I did bad science. I'll look into that. So then here's another difference between const object = LargeStruct.init();
const stuff = []LargeStruct{ object };
cmp_pattern(object, stuff);
// ERROR: cannot convert arg 1 from &const LargeStruct to &const $T
cmp_var(object, stuff);
// cmp_var(a: &const LargeStruct, b: []const LargeStruct)
// no error on invocation. probably get errors from inside the function body. This parallels the issue that |
I don't think Zig is going to have this. #1669 is closer to the direction zig is going. |
So generic functions typically look something like this:
fn cmp(comptime T: type, a: T, b: T)
Have you considered doing like Jai and let the following be short for that.
fn cmp(a: $T, b: T)
Here the dollar sign means that the type of this parameter will be picked up by the compiler and assigned to the comptime variable T. It would also work for complex types like
[]$T
.The text was updated successfully, but these errors were encountered: