Why does by_ref not work for File?

Hi experts, why it says the following and what should I do?

error[E0034]: multiple applicable items in scope

    --> src\main.rs:15:27

     |

15   |         let reference = f.by_ref();

     |                           ^^^^^^ multiple `by_ref` found

     |

     = note: candidate #1 is defined in an impl of the trait `std::io::Read` for the type `File`

     = note: candidate #2 is defined in an impl of the trait `std::io::Write` for the type `File`

here is my code:

use std::fs::File;
use std::io::SeekFrom;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {

    let fname = r#"<the-file-path>"#;
    let mut f = File::open(fname)?;
    
    f.seek(SeekFrom::Start(678))?;
    {
        let reference = f.by_ref();
    }

    Ok(())
}

Thanks!

That error means that it found several by_ref methods and wasn't sure which one to call. In your case, I would probably just write this instead:

let reference = &mut f;

Hi Alice,

That works. Thank you!

Given that there are multiple applicable items in scope, how can I choose the one explicitly? For example,

trait T1 {
    fn foo(&self) -> i32;
}
trait T2 {
    fn bar(&self) -> i32;
}
trait T3 {
    fn bar(&self) -> i32;
}

struct S(i32);
impl T1 for S {
    fn foo(&self) -> i32 {
        self.0 + 1
    }
}
impl T2 for S {
    fn bar(&self) -> i32 {
        self.0 + 2
    }
}
impl T3 for S {
    fn bar(&self) -> i32 {
        self.0 + 3
    }
}

fn main() {
    let s = S(0);
    let t1 = s.foo();   // ok
    let t2 = s.bar();   // error: T2 or T3 ??

    println!("{}, {}", t1, t2);
}

Is there a way to explicitly call the T2 one?

Thanks in advance.

Yes, you can do this:

fn main() {
    let s = S(0);
    let t1 = s.foo();
    let t2 = T2::bar(&s);

    println!("{}, {}", t1, t2);
}

Great. You just save my day.

Could you please kindly show me some reference for the T2::bar(&s) ?

All method calls can be called with StructOrTraitName::method_name(&the_self_argument). I'm just using that. You can read more here.

There's also some mention of this syntax in the book.

Advanced Traits - The Rust Programming Language

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.