quick introduction, I came from python I have studied it by myself, and now I'm trying to learn Rust. I find it a bit confusing.
I have a main.rs
file and other .rs
files in the src
directory just to have cleaner and organized code, as each of these other files do specific tasks and the main.rs
just put all together with a simple CLI.
I just wanna test a single of these .rs
file, or even a single fn
inside to check if the result is what I am expecting.
How can I do that? It's simple, it's stupid, but I have read around and found nothing that could help me in the end.
I read this, where it talks about making a tests
folder and then using cargo test
, I've done it, but it still runs the src/main.rs
instead of what I have put in tests
. BTW I'm using CLion with the Rust plugin.
Sorry if this is somewhat a duplicate, I looked around but I didn't found an answer.
Edit 2023-09-01: A related feature is now available as experimental in rust (cargo) nightly. See:
This functionality is not really part of cargo, but there are some crates that do it. The one I'm most familiar with is rust-script. It works with a hashbang like #!/usr/bin/env rust-script
at the top of your script, then run it with ./script.rs
. You can even specify dependencies in the script which get parsed out of some special comments.
Otherwise uou can compile single files directly with rustc
, but managing dependencies, etc. can be complicated.
Edit: Sorry yes - it looks like you're trying to write/run tests. The page you linked in the book should cover what you're trying to do. I'm not sure what you mean by "it still runs the src/main.rs
instead of what I have put in tests
". Do you have mod tests
in main.rs
as well?