How should you format your headers in Rust?

How should you format your headers in Rust???

I'm learned about Rust while learning C# and after I learned C# I wanted to learn Rust but I don't know what the correct way to format your headers is, I would format it like this.

use std;
use std::result::Result;
use std::path::Path;
use std::path::PathBuf;

fn main() {
    println!("Hello, world!");
}

First off, rust has no concept of headers.

Secondly, the formatting you showed in the example is fine, but if you're really concerned about it, you can just use rustfmt.

Lastly, if you are talking about the use statements (aka imports), it's better to group related imports together, so


use std::path::Path;
use std::path::PathBuf;

is better written as


use std::path::{Path, PathBuf};
1 Like

Ok thanks, I didn't know what the term was I just knew Rust was convoluted C++ basically.

That's the most particular description of Rust I have seen so far :joy:

I guess you would call these "headers" just "use declarations" or "imports", as already mentioned.
rustfmt will automatically sort them alphabetically for you and also group them if you set the merge_imports option to true in your rustfmt.toml.

1 Like

That triggered such an instant, explosive laugh I now have coffee sprayed all over the place. Thank you, that made my day.

Trust me, there is no programming language more convoluted than C++. You would be well advised never to look at it.

More seriously, the last thing you need to worry about is formatting in Rust. Just use cargo fmt and it's done. Use the standard settings out of the box so that your code is formatted consistently with all the other Rust code in the world. That will make life easier on any future readers of your code.

Except: I did not know about the merge_imports option that dthul suggested. That sounds like an excellent idea.

There are no headers in Rust, as in C/C++ header files. Everything is in Rust source files *.rs. What is included in your project is specified in it's Cargo.toml file.

As far as I can tell those use clauses are only creating short hand names for things that are already available to the project.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.