Why does count_ones not work if I don't specify the number's type?


Keywords:methods 


Question: 

Why do I need to explicitly declare type i32 for a number to be able to use count_ones on it?

fn main() {
    let x: i32 = 5;
    println!("{}", x.count_ones());
}

If I wrote let x = 5; I would get an error no method named 'count_ones' found for type '{integer}' in the current scope. Why doesn't it work that way?


1 Answer: 

The method count_ones is not provided by a trait shared among integral types - it's implemented separately for each of them. This means you need to specify the type in order for that method to be applicable to the number you want to use it on - the compiler needs to know which type's implementation to use.

In addition, if you are wondering why in this case the compiler doesn't know that let x = 5; without a specified type should assign i32 (the default integral type) and use its implementation of count_ones, it is just not that compilation stage yet - the default types are assigned after the method and function names are resolved.