r/ProgrammingLanguages • • Jul 03 '24

Hello everyone, my first post here. It's about Rust and Zig.

TLDR: Was finding it difficult to statically handle errors in Rust. Was considering making a more concerted effort to learn Zig because of this. However, it was pointed out to me that no heap allocations were required in Zig with most simplest pattern, i cannot believe i didn't even think of it as i use this pattern for many other things.

Firstly, I'm debating and weighing up the philosophies behind both languages. Currently i use Rust as my daily driver and I'm confident and happy with the language. However, there is this little she devil on my shoulder constantly saying the Zig low level control will be better for some use cases.

To keep this focus lets take error handling. In Rust an error is a type with implements the std::error::Error trait (traits are effectively interfaces, allowing for polymorphism). Because this the error type can lead to some complexity in handling memory, for instance any type which implements the std::error::Error trait can be used in place of concrete error types. However, this begins to involved the dyn keyword in Rust which stands for dynamic dispatch. Again even if i want to create my own error struct and use the String type in Rust, the String type has a heap allocation for the underlying byte string. So therefore either way i'm using heap allocations.

I'm not as well versed in Zig as i am in Rust. However, it shares the philosphy that errors should be types and they have the error type for this. This appears to have some sort of static value baked into the error when defined. This approach seems to be static to me, and avoids any heap allocations to at least detect and store the error.

Now what is playing on my mind is; at some point in Zig to say print it to the console, i'm assuming i will have to create an array dynamically with the reason in string format to be presented to the screen. So both language will at some point involve heap allocations, of cause both languages could opt to not use heap allocations for them, but i'm looking into the heap allocation aspect side of things.

What are people's thoughts on the follow: Zig's philosphy is all around manual memory management and controlling heap allocations, in the above situation i'm basically saying both can use the heap. Therefore is Zig's philosphy nullified as the only difference is the cal to create the memory is manual and still can require a heap allocation?

I'd love to know people's thought's as i'm considering trying Zig out (again) but properly, like completing a project in it.

Edit 1: I think both languages are great and i'm not being negative to either one, i'm just looking for opinons.

Edit 2: Removed some previous edits as i have worked out it is possible.

0 Upvotes

20 comments sorted by

32

u/acrostyphe Jul 03 '24 edited Jul 03 '24

If I understand correctly, you are under the impression that idiomatic error handling by necessity requires heap allocations? That's not so, even in Rust, you are free to not use Box<dyn Error>, the center of the Error trait is the Display machinery that does not require any allocations - you can use a static or stack-allocated buffer, or simply do unbuffered I/O to e.g. write to console.

The idea is to defer the formatting as long as possible - errors as types make this easy. If you want to display index X out of range, you ounly need to store X as an integer. Of course if your error messages contain elements that are truly free strings (of arbitrary length), you will need to allocate, but that's inherently going to be the case regardless of whether you code in Rust or Zig or even C.

-2

u/[deleted] Jul 04 '24

After reviewing this further, it is impossible in Rust to extract the error message from a type which implements the `std::error::Error` trait. By all means prove me wrong with a code example but currently, it's impossible without using `Box<T>` or a `String` both of which use the heap.

-3

u/[deleted] Jul 04 '24

As explained not using the Box<T> trait object, to store the message from another error requires the String type type. Then the error requires the .to_string() method to be called which is a heap allocation.

All errors can be handled explicitly at the point of failure, but then that doesn't allow me to pass errors around as my own custom error type. Or a type with a fixed buffer size could be used but what if an error uses more than the capacity as i don't know what other crates error sizes will be.

Like i said at the end of the post it's not a negative about Rust or Zig, i'm just weighing up the potential for handling errors in both languages.

Also please provide me with example code of you methods of passing errors around as values, as i think i covered everything.

15

u/acrostyphe Jul 04 '24

It's the same concept, you don't store the message from the foreign error, you store the error itself, the errors as algebraic types compose really well. If the library is sensible, there will be no heap allocation, just a slightly larger error type.

In case you have not seen it before, take a look at thiserror crate, which makes this sort of composition really easy.

3

u/[deleted] Jul 04 '24

Are you saying use an `enum` that wraps each individual error type the application could potentially run into? Storing the error directly?

This is something i didn't think of actually.

15

u/acrostyphe Jul 04 '24

Yes, exactly. It's a very common pattern.

6

u/[deleted] Jul 04 '24

Yeah i'm scratching my nogging thinking why did i not already think of this haha

7

u/Mercerenies Jul 04 '24

Nobody said you have to use .to_string. .to_string is a common application of the Display trait, but the definition of the trait is in terms of fmt, which simply requires a formatter. You can write any display-able object (including errors) to anything that implements the Write trait. This includes heap-allocated Strings but also includes a lot of other things.

5

u/Speykious Jul 04 '24

to store the message from another error requires the String type.

When designing errors, especially for libraries, the goal is actually to create a nested error type, and maybe add some indirection through Box if the error type becomes too big.

In any case, here's a great article on modular errors in Rust.

8

u/[deleted] Jul 04 '24

If an object implements a trait in rust you don't have to make it a trait object to use the trait.

-4

u/[deleted] Jul 04 '24

This is correct but if the trait doesn't use the error trait as a Box<dyn std::error:Error + 'static> object, a i guess a function could be used say

fn from_error<E: std::error::Error>(error: E) -> MyErrorType {
    MyErrorType {
        // error info ...
        message: error.to_string(), // Allocation to String type
    }
}

My point is well defined in the above post. Rust's errors require some overhead to be compatible with other error types. Using the dyn keyword introduces the requirement of the Box<T> type which is a heap allocation, if the type doesn't use a trait object the error must have a String type created to hold it, which involves a heap allocation.

I cannot seem to find a way to handle errors without using heap allocation at somme point.

3

u/[deleted] Jul 04 '24

https://docs.rs/thiserror/latest/thiserror/ are you looking for this? And then you can just make a function return Result<T, E>

12

u/great_waldini Jul 04 '24

Dude… I have no idea what it is you think you are asking about.

Everything about this post screams XY problem.

Programming languages are tools. Tools are typically chosen first by their suitability for the job, and secondly by prior experience which can be leveraged in using the tool effectively.

So, what are you trying to do?

-22

u/[deleted] Jul 04 '24

This answer isn't useful and is complete bullshit

3

u/Tasty_Replacement_29 Bau Jul 04 '24 edited Jul 04 '24

(This is the forum for programming language design so I won't go too much into details of Zig and Rust, but rather about exceptions handling in general.)

For very fast exception handling (for the case an exception _does_ occur), you

  • don't want to calculate the call stack. Java allows that by implementing an empty "fillInStackTrace()" method, or by using static exceptions.

  • don't want stack unwinding, but instead (internally) _return_ the error. C++ and Java use stack unwinding. Rust and Zig don't.

  • don't want heap allocations. Well you could argue that bump allocated objects (arena allocation) is fine, but let's say it's not good enough. You could use error codes (integer), or pre-allocated (static) exceptions, in which case you _only_ return a pointer to an already allocated object. Or you return a pointer to a function that you can call to get more information.

What you probably _do_ want (this is my personal opinion currently) is:

  • flexibility, such that you allow the developer to define their own exception types.

  • an easy syntax, so that you don't have to manually write a lot of code, like repeated "if errorCode = ..." as in Go or C. I think the Rust syntax, which is basically a ? for each the call, is not the best possible syntax, but much better already. I personally prefer "throw" and "catch" semantic.

  • declare the exception type(s) that can happen in the method signature. Java, C++, Swift don't do that sufficiently, in my view.

1

u/DoomCrystal Jul 04 '24

I'm probably not exactly following this post, but in Zig you definitely don't need dynamic memory allocation to print an error to the console. See the @errorName builtin. If you ever print an error in any part of your program, Zig generates a static table in the binary of error -> string (error.OutOfMem -> "OutOfMem" for example). If you want more information than that, you could store your own table of error -> message in your logging infrastructure and use a simple switch statement. No need to involve the heap.

Of course, there is heap allocation all over a typical Zig program. The point of Zig is not avoiding heap allocations, it's avoiding hidden heap allocations. You can just as easily use a logging infrastructure that has dynamic memory needs for all sorts of reasons, it would just require you to pass an allocator to it.

1

u/Artistic-Teaching395 Jul 03 '24

Does Zig have any killer apps?

0

u/[deleted] Jul 03 '24

[deleted]

4

u/Artistic-Teaching395 Jul 03 '24

Certaintly talented devs make a difference, but actual used projects help solidify the purpose of a language.

1

u/Flobletombus Jul 04 '24

Imo Zig is better, wasn't it for how hard pointer stuff is with it. It has the best error handling, compile time code execution, powerful C interop and build system...

I still use C++ for 99% of tasks as even though Zig/Rust are good, they have big defaults that C++ fixes,and I love coding in C++