CodeBlanks Logo Icon CodeBlanks

#[inline]

Learn the #[inline] attribute and its effects.

#[inline]

Inlining replaces a call with the function body; the call cost disappears and later optimizations open up. The compiler decides this itself within a crate. The attributes give hints:

#[inline]          // so it can be inlined outside the crate too
pub fn kare(x: i32) -> i32 { x * x }

#[inline(always)]  // a strong request (not a guarantee)
fn sicak(x: u8) -> u8 { x ^ 0x55 }

#[inline(never)]   // shows separately in profiles, keeps code small
fn soguk_yol() { .. }

Generic functions don't need #[inline], since they're recompiled in every crate anyway.

Hot and cold paths

Moving rarely run error paths into a separate function and marking it #[cold] and #[inline(never)] keeps the frequently run path small and fast:

#[cold]
#[inline(never)]
fn tasma_hatasi(i: usize) -> ! {
    panic!("indeks {i} sınır dışında")
}

fn al(v: &[u32], i: usize) -> u32 {
    if i >= v.len() { tasma_hatasi(i) }
    v[i]
}

! (the never type) says the function never returns.

Practice Inlining hints

Write #[inline] fn kare(x: i32) -> i32 and #[inline(never)] fn kup(x: i32) -> i32. Print the result of kare(3) + kup(2).

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
#[inline]
fn kare(x: i32) -> i32 {
    x * x
}

#[inline(never)]
fn kup(x: i32) -> i32 {
    x * x * x
}

fn main() {
    println!("{}", kare(3) + kup(2));
}

Expected output

17

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is adding <code>#[inline(always)]</code> to every function a bad idea?

  • It's unsafe
  • Code grows, the instruction cache overflows and the program can slow down Correct answer
  • It doesn't compile
  • It has no effect

Explanation: Inlining is a trade-off; the compiler's heuristics are usually good. Don't force it without a profile showing the need.

2 Inlining hint

Question
#[____]
pub fn kare(x: i32) -> i32 {
    x * x
}
Answer
#[inline]
pub fn kare(x: i32) -> i32 {
    x * x
}

Explanation: #[inline] makes the function inlinable outside the crate too.

3 Attribute and purpose

Term Meaning
#[inline] Cross-crate inlining
#[inline(always)] Strong request
#[inline(never)] Never inline
#[cold] Rare path

All lessons in Expert