'Why aren't traits necessary in scope when they are not used in a method-like style?
When I implement a trait for a given struct, I can obviously only use it by bringing the trait into scope. For example:
// file1.rs
pub struct MyStruct {
value: u64;
}
impl MyStruct {
pub fn new(value: u64) -> MyStruct {
MyStruct { value }
}
}
impl BitOr<MyStruct> for MyStruct {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self::new(self.value | rhs.value)
}
}
// main.rs
use file1::MyStruct;
let t1 = MyStruct::new(10u64);
let t2 = MyStruct::new(15u64);
let t3 = t1.bitor(t2); // This gives a compilation error unless std::ops::BitOr is in scope
The compiler has some useful warnings about this behaviour:
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use std::ops::BitOr;
|
However, if I replace let t3 = t1.bitor(t2); with let t3 = t1 | t2;, then the code compiles without errors even if std::ops::BitOr is not in scope. Why is that?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
