Inlining assembly code
In Rust, we can embed assembly code. This should be extremely rare, but one can imagine situations where this might be useful, for example, when you require utmost performance or very low-level control. But of course, the portability of your code and perhaps its stability decrease when doing this. The Rust compiler will probably generate better assembly code than you would write, so it isn't worth the effort most of the time.
The mechanism works by using the asm!
macro, as in this example, where we calculate a - b
in the subtract
function by calling the assembly code:
// code from Chapter 10/code/asm.rs: #![feature(asm)] fn subtract(a: i32, b: i32) -> i32 { let sub: i32; unsafe { asm!("sub $2, $1; mov $1, $0" : "=r"(sub) : "r"(a), "r"(b) ); } sub } fn main() { println!("{}", subtract(42, 7))
This prints out the result
.35
asm!
can only be used with the feature gate #![feature(asm)]
.
asm!
has a number of parameters separated...