Rust - AsRef usage

less than 1 minute read

AsRef is useful for generic function on accepting specific reference such as str or Path as trait bounds.

Please see the below example.

1
2
3
4
5
6
7
fn format_str(s: str) {
  
}

fn format_string(s: String) {

}

Above two function can be replaced by the below a single function with generic type which implement str reference.

1
2
3
fn format<S: AsRef<str>> (s: S) {
  let s_ref = s.as_ref()
}

https://doc.rust-lang.org/std/convert/trait.AsRef.html
https://www.philipdaniels.com/blog/2019/rust-api-design/

Categories:

Updated: