-- Leo's gemini proxy

-- Connecting to gemini.hitchhiker-linux.org:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini;lang=en-US

Re: Handling Optional Values in Rust macro_rules

2022-11-09

An interesting post on implementing Rust macros:

gemini://hoseki.iensu.me/posts/handling-optionals-in-rust-macro-rules.gmi


I love Rust, but there are certain things which I don't feel it does very well. One thing that I think was a mistake in C was the entire preprocessor, and most especially macros. I'm not exactly a fan of macros in Rust, either. I think this posts central premise is a good example where I can demonstrate a language which has a better solution.


The original post involves implementing some Rust code which can convert optional enum values to strings, and vice versa. I'm going to briefly show the same sort of thing in Zig, which has great compile time reflection.


const std = @import("std");
const meta = std.meta;

pub enum MyEnum = {
    typeOne,
    typeTwo,
    typeThree,

    pub fn tryToString(self: ?MyEnum) ?[]const u8 {
        if (self) |s| {
            return meta.tagName(s);
        } else return null;
    }

    pub fn tryFromString(str: ?[]const u8) ?MyEnum {
        if (str) |s| {
            return meta.stringToEnum(MyEnum, s);
        } else return null;
    }
};

And thats it. The entire `meta` namespace is part of the standard library in Zig and deals with these sorts of compile time scenarios, allowing you to do a lot of conditional things based on what the compiler knows about the types at compile time. It was quite surprising to me to see just how much meta programming can be done with this system, and it makes me hate macros even more than before. Why have a separate sub-language for meta-programming? Zig shows that it's pretty much unneccessary. \Rantmode_off


That said, I tend to prefer Rust overall for real world use these days...


Tags for this page

rust

zig

programming


Home

All posts


All content for this site is licensed as CC BY-SA.

© 2022 by JeanG3nie

Finger

Contact

-- Response ended

-- Page fetched on Mon May 20 12:08:33 2024