Anytype best practices

So for background I’ve been using zig since ~0.12 but I’ve only recently really dug into the comptime/metaprogramming features. Whenever I’ve had to use anytype (or like an inline for that calls the same fn/access the same field, that sort of thing), I get a bad taste in my mouth. It feels like every implicit contract I add is going to make retracing my steps later that much harder. Maybe that’s just the trade-off, but my question is:

Does anyone have examples of strategies/design patterns I’m missing out on that can help narrow anytype/make it more explicit? For now I’m just trying to add good comments and putting in a few @compileErrors.

My main advice would be to only use it, if it is actually required, so if an explicitly declared struct or tagged union type would work to model the parameter then use that, instead of using anytype out of laziness.

Then when you do use it, make sure you have doc tests of the function (test functionName {...}) that demonstrate all the possible usecases, that way you have both testing and usage examples showing up in the documentation / making sure the intended api is documented and that it remains supported with future changes.

7 Likes

Yea my current project is using a good amount of anytype + interfaces and I’m leaning into interfaces as much as possible. Anytype has kinda been the escape hatch for things I can’t represent otherwise

Why interfaces?

I found that anytype is suitable for expecting a tuple where the length of properties is runtime-known or variable (std.debug.print) while type is good for generics parameters, e.g., std.mem.find, to build a reusable library.

1 Like

Use normal types when you can. Once one thing is generic, every struct that holds it and every function that uses it has to be generic too.

And like @zeeqeeng said, if the type depends on something known at compile time, pass it in, the way std.mem.find takes comptime T: type.

For the anytype that’s left, the @compileErrors you’re adding are the right idea.

1 Like

so for example, in one part of this project:

At startup an array of different function pointers is assembled based on runtime parameters. The function to turn all these many structs into this interface (literally just looping through every decl and calling toInterface()) is accomplished through an inline for loop/anytype situation, but everything from then on uses the interface. It’s surely possible to do the same thing without an interface (it’s already halfway there) but this seemed like the right place to draw the boundary

But why male models?

Sorry, I just couldn’t resist. Apologies to moderators.

nono, my question was less intelligent than the one you answered. I meant why does your project have interfaces?

I’m repeatedly looping through an arbitrarily sized array of pointers to structs that operate on the same data. There could even be duplicates that just have different options set up, so an interface seemed appropriate. The program is extremely i/o bottlenecked so I figure the most important thing is finding an effective way of sharing the data (i.e. every struct operates on each delimited chunk before moving on)

By “implicit contract” do you mean the field/function names you access on the item? Calling `x.quack()` implies it must be able to quack?

If I’ve understood that part ok, I’m not understanding what aspect of “retracing your steps” leaves you worried. I just want to understand your concerns a bit more.

For now I’m just trying to add good comments and putting in a few @compileErrors.

Good comments are never a bad thing[1].

I don’t personally see the point of adding compilation errors[2]. The compiler has to resolve everything to concrete types during compilation. If it can’t, because it’s ambiguous, the program will not compile. If it can resolve the type, but the “implicit contract” isn’t honoured, that will be an error. You’ll be told exactly which error violates the contract and how.

Adding your own compilation errors to something that is already a compilation error seems redundant to me.


  1. If you can define “good” ↩︎

  2. …for this ↩︎

Yea pretty much. If I want to add something that has to include specific functions/contain certain fields, I prefer an explicit spec from the type system instead of relying on comments. I also like my LSP knowing what’s going on, but I’m assuming ZLS will have some kind of comptime type inspection one day.

My trepidation was mostly vibes-based and I would not be all that surprised if this ends up being a nothing-burger down the line

So, you could add asserts that check that values have the decls you rely on:

fn quack_it(x: anytype) void {
    assert(@hasDecl(@TypeOf(x), "quack"));
    return x.quack();
}

…but I don’t think it’s very readable, and the compiler will already check that in a stricter way[1]. It can also fall out of date the same way a comment can.

// This will only work with something that can quack and bark.
fn quack_it(x: anytype) void {
    assert(@hasDecl(@TypeOf(x), "quack"));
    return x.bark();
}

At that point, I think all you’re adding is bad documentation, so use a better documentation construct… comments.

This will be interesting to see what they come up with. I think all the information from the compiler will be available, but coming up with a nice UI will be a challenge I think. Remember that the code gets duplicated in the compiler for every different type that the function gets called with. Folding the type annotations for multiple versions of the code onto a single source version is going to be hard to do in a readable way.


Bottom Line: I think the “bad taste” you’re experiencing is a lack of confidence in the language being able to catch you when you fall. So I really suggest playing with the feature and understanding it’s limitations. It’s comptime and that really limits how far you can get yourself into trouble with it. Static types only. Even tagged-unions can only be handled in generic ways.

I think your misgivings are probably much more relevant when applied to a runtime duck-typing system, because there the compiler has to relinquish the type-check to the runtime environment. That’s not Zig. That’s Python, or Ruby, or Smalltalk.


  1. …making sure it’s also callable ↩︎

1 Like

off topic but:

Idk why they’d do that in the first place, it is the function that is defining what is required not the callers.

But perhaps zls will be able to know what is required to filter completions for the caller, and perhaps within the function too.

The main appeal is for zls to know the resulting values, including types, of comptime code. Currently his is what most people find annoying with zls.

2 Likes

I think this is a fair assessment that puts me at ease a bit. Big part of my background is in js/ts

You might be surprised at the amount of trouble I’ve gotten myself into so far