How to write idiomatic rust?

I'm more of a functional programmer and I've looked over a lot of medium articles where the tutor fp people for writing rust. I don't know if there is an idiomatic way of writing rust, that looks clean and rusty(for lack of my vocab).

I don't think fp way is idiomatic but if there is a second close which doesn't compromise over performance over style. But I don't want to write C/C++ like imperative code. I believe it must be reusable and atomic.

I would love to get some help, and also how I can use clippy I use vscode's rls extension.

Thanks

Apart from clippy, there are also API guidelines for libraries that might give you an idea what is considered a good Rust code.

1 Like

"rust.clippy_preference": "on" in your settings.json, I think.

I wouldn't say FP style is unidiomatic for Rust. The design of Rust is weighted pretty heavily in favor of FP over imperative programming. For instance, iterator chains can often be optimized better than the corresponding imperative loop.

I guess it depends on what aspects of FP you're talking about. Rust doesn't have tail call optimization, so recursive functions are generally a bad idea. Many recursive functions can be rewritten as a fold on an Iterator, though, which is perfectly idiomatic.

Rust unfortunately does not have HKTs currently, so you may have to settle for writing code that's not as generic as you would like it to be. Sometimes you can simulate it by writing macros (basically, relying on duck-typing). Alternatively, some problems that would be solved with HKTs can be solved a fair bit more verbosely using traits. (possibly with custom #[derive]s). It depends on the problem.

3 Likes