Why doesn't count_ones work if I don't specify the type of number?

Why do I need to explicitly declare a type i32for a number in order to be able to use count_oneson 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 is this not working?

+6
source share
1 answer

The method is count_onesnot provided by a feature shared between integral types - it is implemented separately for each of them. This means that you need to specify a type so that this method is applicable to the number on which you want to use it - the compiler must know which type implementation to use.

, , , let x = 5; i32 ( ) count_ones, - .

+6

All Articles