Live data from Hacker News

My Struggles with Rust

compileandrun.com

31–40 of 329 posts

Re: My Struggles with Rust

#31
Hello Justin Turpin! Sorry to hear your struggles with rust. It's always going to be a bit more verbose using rust than Python due to type information, but I think there are some things we could do to simplify your code. Would you be comfortable posting the 20 line code for us to review? I didn't see a link in your post.

Anyway, so some things that could make your script easier:

* for simple scripts I tend to use the `.expect` method if I plan on killing the program if there is an error. It's just like unwrap, but it will print out a custom error message. So you could write something like this to get a file:

    let mut file = File::open("conf.json")
        .expect("could not open file");
(Aside: I never liked the method name `expect` for this, but is too late to do anything about that now).

* next, you don't have to create a struct for serde if you don't want to. serde_derive is definitely cool and magical, but it can be too magical for one off scripts. Instead you could use serde_jaon::Value [0], which is roughly equivalent to when python's json parser would produce. * next, serde_json has a function called from from_reader [1], which you can use to parse directly from a `Read` type. So combined with Value you would get:

    let config: Value = serde::from_reader(file)
        .expect("config has invalid json");
* Next you could get the config values out with some methods on Value:

    let jenkins_server = config.get("jenkins_server")
        .expect("jenkins_server key not in config")
        .as_str()
        .expect("jenkins_server key is not a string");
There might be some other things we could simplify. Just let us know how to help.

[0]: https://docs.serde.rs/serde_json/enum.Value.html

[1] https://docs.serde.rs/serde_json/de/fn.from_reader.html

Re: My Struggles with Rust

#32
post #3
post #2

These struggles are real. I don't see a way around them other than just learning them (and then they go away, because you know what code won't work, and don't fight it). It's probably because Rust looks and operates mostly like a high-level language, but still satisfies low-level constraints. e.g. the confusing difference between `&str` and `String` is equivalent of C's `const char * str = ""` vs `char * String = mal…

These struggles are indeed real, but at least as far as verbose error handling goes, remember that Rust is forcing you to handle a lot of things that are silently ignored in Python. Truly equivalent Python code would include a bunch of exception handling and checks for nil.

The author seems to want to not use unwrap() in the rust version when that is basically what is done in the python version. The python version will die with an exception if:

1) the file does not exist

2) the file is not readable

3) the file cannot be parsed

Rust forces you to say you want to panic in these cases (by using unwrap), but beyond that, the behavior is similar.

Re: My Struggles with Rust

#33

Rust's aversion to exceptions is exactly like Go's aversion to generics - a strongly held position that doesn't actually make anyone's life easier.

Monads are a superior form of error handling than exceptions... The only problem is that AFAIK (but I'm still learning it) Rust is missing something equivalent to Haskell's do notation.

> The only problem is that AFAIK (but I'm still learning it) Rust is missing something equivalent to Haskell's do notation.

Rust has essentially specialized do-notation for error handling called the `try!` macro, or more recently, `?`. (`try!` and `?` are exactly equivalent in today's Rust.) Actually, it does just a bit more than standard do-notation would: it also tries to convert your error value at the call site to the error type expected by the return type of the current function.

The problems posed in the OP are pedagogical ones IMO that I hope can be solved. I think the current resource on error handling in the book is good for folks who really want to dive in and figure out the complete story, but it's bad for folks who just want to write code that works without spending a couple hours doing a deep dive. So I think there's room for more targeted pedagogy here.

Re: My Struggles with Rust

#34
The author doesn't really justify why he needed to port the python script to rust in the first place.

Pulling down some JSON, doing a bit of transformation and sending alerts seems like a perfect candidate for a high level language, I don't see any reason why you would port it to Rust unless you had significant performance concerns

Re: My Struggles with Rust

#36

The author doesn't really justify why he needed to port the python script to rust in the first place. Pulling down some JSON, doing a bit of transformation and sending alerts seems like a perfect candidate for a high level language, I don't see any reason why you would port it to Rust unless you had significant performance concerns

> The author doesn't really justify why he needed to port the python script to rust in the first place.

And they don't need to. When I first learned Rust, I tried to write a `filter` function. Why would I ever do that? I could write `filter` much easier in Python, or heck, just use the `filter` method on iterators that is already in the standard library. I did it because I saw it as an opportunity to learn. I wanted to connect something I knew (`filter`) with something I didn't know (Rust).

Re: My Struggles with Rust

#37
post #4

My main gripe with Rust so far has been the unnecessary profusion of Result types, making it hard to process and forward errors. Case in point: the example in the article from the rust documentation that converts errors to strings just to forward them: https://doc.rust-lang.org/book/error-handling.html#the-limit... In practice, I find a type like Google's util::StatusOr ( https://github.com/google/lmctfy/blob/master/…

I think having Result alone does not make error handling complicated, but having different error types for each operation (and concrete result) instead of using one generic error type for all of them does by pushing the job of unifying erros towards the user.

Go works around the problem by Error being an interface, which means any function can return any kind of error without needing to transform it to another form. However Go benefits from the Garbage Collector here - I totally understand why Rust libraries don't want to return heap allocated errors.

Maybe C++ std::error_code/error_condition provides some kind of middle ground: It should not require a dynamic allocation. And yet the framework can be expanded: Different libraries can create their own error codes (categories), and error_codes from different libraries can all be handled in the same way: No need for a function that handles multiple error sources to convert the error_codes into another type.

The downside is that the size of the error structure is really fixed and there's no space to add custom error fields to it for error conditions that might require it. A custom error type in Result can be as big or small as one needs.

Re: My Struggles with Rust

#38
post #2

These struggles are real. I don't see a way around them other than just learning them (and then they go away, because you know what code won't work, and don't fight it). It's probably because Rust looks and operates mostly like a high-level language, but still satisfies low-level constraints. e.g. the confusing difference between `&str` and `String` is equivalent of C's `const char * str = ""` vs `char * String = mal…

I don't know Rust, or the general direction of the community around it.

Is there some chance, that over time, most popular functionality will end up in well architected crates that abstract away some of these complaints?

A bad example, perhaps, because they probably go too far with it, but a lot of java's verbosity fades away because there's a rich ecosystem of libraries that already know how to do what you're trying to do. There is, of course, a downside to that...important implementation details become opaque to the users of these libraries.

Re: My Struggles with Rust

#39

I was under the impression that the (somewhat) verbose syntax for error handling and memory management via the type system was a necessary side effect of Rusts entire point of existence: a compiler-guaranteed safe systems language. Neither Python nor C force you in any way to pay attention to errors, making simple scripts much easier to write. I guess I'm just surprised people think that Rust should be as simple to u…

I think the complaint is more that Rust has seemingly tried very hard to make error handling "simple". But in the process it has managed to invent a whole series of new idioms and special syntax that is alien to pretty much everyone. There's a thread in /r/rust about this same article where you can look and see people suggesting all sorts of ways to write this that are split into clear sedimentary layers depending on when the writer learned the language.

At this point the cognitive load required to read and understand Rust implementations of "typical" practical problems is rather higher than it is for C++. And it seems to be getting steadily worse from my perspective on the outside.

Re: My Struggles with Rust

#40

Earlier quoted context omitted.

I find result types to be much easier to understand and work with than exceptions. Result types can be handled by the type system, even when you have checked exceptions in java, there are still exceptions that aren't checked, and the syntax for the checking becomes monstrous.

Implicit return codes (e.g. return int, -1 means error, 0+ means OK) are equivalent to unchecked exceptions. Explicit return codes, where you must process them or compiler will yell at you are equivalent to checked exceptions. I think, that checked exceptions are a good idea, but they must be improved. E.g. Rust have syntax for almost implicit converting one error to another and return it; checked exceptions could us…

Yes, exceptions are better than return codes, but I would argue Result types are better than exceptions. Checked exceptions in Java have their issues. Exceptions in C++ are odd beasts (though that's getting better, they're still not checked and therefor basically anything that isn't noexcept can throw them (oh wait! noexcept can throw! it just crashes immediately)).
Post reply on HN