Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Can you give an example of something that's easier to reason about (e.g., an error that's easier to spot) with Zig's comptime than with macros?

Rust proc_macros takes a stream of tokens and return a stream of tokens. If your macro meant to return an instance of a specific type, it must output the correct tokens which create that instance via existing interfaces. There's some really ugly indirection in trying to understand what's going on.

This is always harder to reason about than Zig's equivalent, because in Zig you just return the thing that you want to return.



How does it work if I wanted to construct a type (and maybe a set of helper types. some related functions, etc.), rather than an instance of a type?

If I just wanted to construct an instance of a specific type at compile time in Rust, I'd probably be using a const fn instead of a macro.


You return the type directly. You can then declare things to be of this type. Eg, from the Zig docs, here's how to construct a generic List type (note the comptime declaration of the generic parameter):

  fn List(comptime T: type) type {
      return struct {
          items: []T,
          len: usize,
      };
  }

  // The generic List data structure can be instantiated by passing in a type:
  var buffer: [10]i32 = undefined;
  var list = List(i32){
      .items = &buffer,
      .len = 0,
  };




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: