r/rust • • 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

8 comments sorted by

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

1

u/ninja-Nithin 1d ago

can i remove and overwrite existing fn, when two different lib add fn foo() in same lib which one compiler choose

And trait only exist in rust?

5

u/XalGaming 1d ago

When there is a conflict of function names, the function directly implemented on a type takes precedence.

To call the trait function with the same name you do Bar::bar(&foo) or <Foo as Bar>::bar(&foo)

3

u/an_0w1 1d ago

You cannot remove or overwrite methods. If you add implement a method with the same name as another traits method then you need to use the full method name MyTrait::foo(&bar) instead of bar.foo() assuming both traits are in scope.

4

u/zettui 1d ago

use fs2::FileExt just brings the trait into scope, fs2 has an impl FileExt for File so 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 toolchain file.unlock() is actually calling the std one.

2

u/rustcurious 17h ago

Traits explained in detail:  https://youtu.be/RKojTb9IVJc