#Generic type constraints?

1 messages · Page 1 of 1 (latest)

quick wing
#

Say I want to write a sort function for an array of a generic type, how would I constrain that generic type to something that can be ordered?

In Rust that would be

fn sort<T: Ord>(array: &mut [T]) {}

How do I achieve this in Zig without using anytype and leaving it to duck typing? Would like some method that can be applied to more than just this example

faint spoke
#

For generic sorting:
Zig doesn't have operator overloading, so only basic integers, floats, etc have < operator style comparison. I would take a look at the implementation of std.sort: https://github.com/ziglang/zig/blob/a07f288eb1772ac25fd0785b142c6ee7e09b2986/lib/std/sort.zig#L17C1-L17C1

The conventional Zig way to do generics really is to just leave it to compile time duck-typing. You can do some manual type checking with builtins like @hasDecl, @typeInfo, etc. There are also some helpers defined in std.meta.

A shameless self plug: I've been playing around with a type trait library, but it's just a proof of concept exploratory kind of thing: https://github.com/permutationlock/zig_type_traits

quick wing
#

Fair enough, pretty much what I expected

#

Cool library though, having implemented something similar to traits in a language of my own, never really seen it done as a library

#

I assume foo(x: anytype) is more "idiomatic" than foo(comptime T: type, x: T)?

#

Is there any semantic difference between the two?

#

Other than if it's used multiple times in the same signature, in which case the difference is that it ensures both types are the same

faint spoke
#

They can be meaningfully different, but it's most obvious if you want to do things like take a slice of a type T:

pub fn generic1(comptime T: type, slice: []T) //...
pub fn generic2(slice: anytype) //...

Using generic1 we can get things like type coercion from *[_]T, whereas generic2 will have a different function generated for each type it's called with at comptime.

quick wing
#

Ah, okay, that makes sense