Ashish Singh
Ashish Singh

Reputation: 759

Trait needs to be imported in current scope even though object module implement the trait

I want a character one at a time from BytesMut object. For this purpose, I used the get_u8() from the bytes::Buf trait.

Since, BytesMut implements bytes::Buf, I was hoping that I could directly call get_u8 on BytesMut object without having to import use bytes::Buf trait in the file where I am calling get_u8() on the BytesMut object.

The error that I get is:

no method named `get_u8` found for struct `BytesMut` in the current scope
items from traits can only be used if the trait is in scope.

I get the error and am aware that I have to import the trait in the current file with use bytes::Buf. What I am not sure about is the rationale behind this implementation.

Upvotes: 3

Views: 1970

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70397

Rust traits do not have to be implemented inside the structure's own impl. A trait can, generally speaking, be implemented in the crate that defines either the structure or the trait (the exact rules are a bit more complicated because of the presence of blanket impls, reference types, and multi-parameter traits). So if you call foo.bar on foo of type Foo, then that could actually be the bar method on trait Bar which is in some crate in the middle of nowhere that isn't at all related to the crate that defined Foo.

Rust can't search every possible crate installed on your machine for the method. That would slow compilation down to a crawl and also create some very confusing error messages. Instead, Rust requires that the trait method be in-scope at the time of the call.

// foo.rs (in crate my_foo)
pub struct Foo;

// bar.rs (in crate my_bar)
pub trait Bar {
  fn bar(&self);
}

impl Bar for Foo {
  fn bar(&self) {
    println!("Hello :)");
  }
}

In this case, the implementation impl Bar for Foo is not in the same file (or even the same crate) as Foo itself, so unless Rust requires that you have the trait method in-scope, it would have no idea what bar is, even if Foo is in-scope.

Upvotes: 2

Related Questions