Why do we have String::len?

Not exactly: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5d5614070a96417cad98a988c6e8d66c

fn foo(_f: impl Fn(&String) -> usize) {}

fn string_len(x: &String) -> usize { x.len() }
fn str_len(x: &str) -> usize { x.len() }

fn main() {
    foo(string_len); // Works
    foo(str_len); // ERROR: type mismatch in function arguments
}

The problem is that there are no function coercions. So something like .map(String::len) and .map(str::len) are different -- one can't just always use the more general one.

5 Likes