如果我正确理解了这个问题,那么您在问两件事:
- 编译器会内联调用
magnitude吗?
- 如果
square_magnitude 本身声明为inline,即使square_magnitude 的代码在特征中不可用,编译器是否能够内联对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
但请注意,compiler will not inline square_magnitude inside magnitude if square_magnitude is not declared inline itself:
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