我知道特质的方法没有一个体,所以没有任何内联。但有没有任何意义来标记它的默认实现?
trait Magnitude {
fn square_magnitude( &self ) -> f64;
#[inline]
fn magnitude( &self ) -> f64 {
self.square_magnitude().sqrt()
}
}
我是否需要重写整个方法体并在实现类型特征时用#[inline]
标记这个impl的方法,而不是像上面那样标记trait的方法?
如果我正确理解了这个问题,你会问两件事:
magnitude
吗?square_magnitude
本身被宣布为magnitude
,即使square_magnitude
的代码在特征中不可用,编译器是否能够内联inline
内部对square_magnitude
的调用?至于第一个,没有理由不能。至于第二个答案是肯定的,编译器将能够内联这两个函数,因为在它生成代码时,两个函数的源都可用。这可以在disassembly中看到:
trait Magnitude {
fn square_magnitude( &self ) -> f64;
#[inline]
fn magnitude( &self ) -> f64 {
self.square_magnitude().sqrt()
}
}
struct Vector { x: f64, y: f64 }
impl Magnitude for Vector {
#[inline]
fn square_magnitude (&self) -> f64 {
self.x*self.x + self.y*self.y
}
}
pub fn test (x: f64, y: f64) -> f64 {
let v = Vector { x: x, y: y };
v.magnitude()
}
使用rustc v1.28.0和选项-O
编译:
example::test:
mulsd xmm0, xmm0
mulsd xmm1, xmm1
addsd xmm1, xmm0
xorps xmm0, xmm0
sqrtsd xmm0, xmm1
ret
impl Magnitude for Vector {
fn square_magnitude (&self) -> f64 {
self.x*self.x + self.y*self.y
}
}
产生:
<example::Vector as example::Magnitude>::square_magnitude:
movsd xmm1, qword ptr [rdi]
movsd xmm0, qword ptr [rdi + 8]
mulsd xmm1, xmm1
mulsd xmm0, xmm0
addsd xmm0, xmm1
ret
example::test:
mulsd xmm0, xmm0
mulsd xmm1, xmm1
addsd xmm1, xmm0
xorps xmm0, xmm0
sqrtsd xmm0, xmm1
ret