Skip to content

Instantly share code, notes, and snippets.

@schmee
Last active February 19, 2019 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schmee/e5d4cc79be30caab91d5c781cf9128b6 to your computer and use it in GitHub Desktop.
Save schmee/e5d4cc79be30caab91d5c781cf9128b6 to your computer and use it in GitHub Desktop.
Generic function question
fn S(comptime T: type) type {
return struct {
const Self = @This();
foo: fn (a: T, b: T) bool,
fn init(foo: fn (a: T, b: T) bool) Self {
return Self {
.foo = foo
};
}
};
}
fn greaterThan1(a: u32, b: u32) bool {
return a > b;
}
fn greaterThan2(a: var, b: @typeOf(a)) bool {
return a > b;
}
fn greaterThan3(comptime T: type, a: T, b: T) bool {
return a > b;
}
// This works
pub fn main() void {
const s = S(u32).init(greaterThan1);
warn("{}", s);
}
// ➜ deflate git:(master) ✗ zig build-exe priority_queue.zig && ./priority_queue
// S(u32){ .foo = fn(u32, u32) bool@10c843850 }%
// // No dice!
pub fn main() void {
const s = S(u32).init(greaterThan2);
warn("{}", s);
}
// ➜ deflate git:(master) ✗ zig build-exe priority_queue.zig && ./priority_queue
// /Users/john.schmidt/personal_programming/zig/deflate/priority_queue.zig:380:27: error: expected type 'fn(u32, u32) bool', found 'fn(var,var)var'
// const s = S(u32).init(greaterThan2);
// ^
// /Users/john.schmidt/personal_programming/zig/deflate/priority_queue.zig:380:27: note: only one of the functions is generic
// const s = S(u32).init(greaterThan2);
^
// Naturally, this doesn't work either
pub fn main() void {
const s = S(u32).init(greaterThan3);
warn("{}", s);
}
// ➜ deflate git:(master) ✗ zig build-exe priority_queue.zig && ./priority_queue
// /Users/john.schmidt/personal_programming/zig/deflate/priority_queue.zig:380:27: error: expected type 'fn(u32, u32) bool', found 'fn(type,var,var)var'
// const s = S(u32).init(greaterThan3);
// ^
// /Users/john.schmidt/personal_programming/zig/deflate/priority_queue.zig:380:27: note: only one of the functions is generic
// const s = S(u32).init(greaterThan3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment