Deref Coercion Feeds String Into Str

Pass &String as &str through deref coercion: Box<String> and &Vec also coerce, so function boundaries take &str or slices without callers copying.

RustData Integrity

Code

rustsnippet
25 lines
fn count_bytes(s: &str) -> usize {
    s.len()
}

fn sum(values: &[i32]) -> i32 {
    values.iter().sum()
}

fn main() {
    let owned = String::from("boundary");

    // Deref coercion: &String turns into &str automatically, no as_str() call needed
    println!("len: {}", count_bytes(&owned));

    // A literal is already &str: both sources feed the same parameter type
    println!("len: {}", count_bytes("literal"));

    // Box<String> borrows as &str along the Deref chain
    let boxed: Box<String> = Box::new(String::from("boxed text"));
    println!("len: {}", count_bytes(&boxed));

    // &Vec<i32> coerces to &[i32]: slice parameters accept more callers
    let v = vec![1, 2, 3];
    println!("sum: {}", sum(&v));
}

How it works

Count the functions count_bytes, sum and main as the entire surface area of Deref Coercion Feeds String Into Str.

Points of care

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: fn count_bytes(s: &str) -> usize

The run emits 2 labeled sections — len:, sum: — one per step.

Launch the file; main takes over and steps through count_bytes and sum.

Key statements

values.iter().sum()
}
let boxed: Box<String> = Box::new(String::from("boxed text"));
fn count_bytes(s: &str) -> usize {
s.len()
}

Interactive Tools for This Topic

FAQ

What does Deref Coercion Feeds String Into Str print when run?
Invoke the file as-is — the `len:`, `sum:` prefixes identify which step printed each line.