r/rust • u/ninja-Nithin • 1d ago
🙋 seeking help & advice How trait work
i saw this code in stack overflow
// Source - https://stackoverflow.com/a/45040455
// cargo-deps: fs2
extern crate fs2;
use fs2::FileExt;
use std::io::Result;
use std::env::args;
use std::fs::File;
use std::time::Duration;
use std::thread::sleep;
fn main() {
run().unwrap();
}
fn run() -> Result<()> {
let sleep_seconds = args().nth(1).and_then(|arg| arg.parse().ok()).unwrap_or(0);
let sleep_duration = Duration::from_secs(sleep_seconds);
let file = File::open("file.lock")?;
println!("{}: Preparing to lock file.", sleep_seconds);
file.lock_exclusive()?; // block until this process can lock the file
println!("{}: Obtained lock.", sleep_seconds);
sleep(sleep_duration);
println!("{}: Sleep completed", sleep_seconds);
file.unlock()?;
println!("{}: Released lock, returning", sleep_seconds);
Ok(())
}
in this code what use fs2::FileExt; will do lock_exclusive() and unlock() are used from let file = File::open("file.lock")?;
- fs2 can overwrite another library like adding extra fn
- how rust compiler handle this
- can i create my own lib can provide something like this
- what is trait
0
Upvotes
6
u/Loose-Room459 1d ago
so fs2::FileExt is a trait that adds lock_exclusive and unlock to std File handles, the compiler lets it work because of extension traits, you bring the trait into scope and suddenly File has new methods
yeah you can totally make your own library that does this, just define a trait with the methods you want and implement it for whatever type you're extending, the compiler figures it out at compile time no magic involved
12
u/BravestCheetah 1d ago
https://doc.rust-lang.org/book/ch10-02-traits.html
4
u/zettui 1d ago
use fs2::FileExtjust brings the trait into scope, fs2 has animpl FileExt for Fileso those methods only show up on File in files that import it. nothing gets overwritten and you can write your own the same way (people call it an extension trait), small catch with this exact snippet though: std got its own File::lock/unlock in 1.89, so on a recent toolchainfile.unlock()is actually calling the std one.2
u/rustcurious 17h ago
Traits explained in detail:Â https://youtu.be/RKojTb9IVJc