繁体   English   中英

如果我没有指定数字的类型,为什么count_ones不起作用?

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

为什么我需要为数字显式声明类型i32 count_ones在其上使用count_ones

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

如果我写了let x = 5; 我会得到一个错误no method named 'count_ones' found for type '{integer}' in the current scope 为什么不这样做?

方法count_ones不是由整数类型共享的特征提供的 - 它是为每个类型单独实现的。 这意味着您需要指定类型,以使该方法适用于您要使用它的数字 - 编译器需要知道要使用哪种类型的实现。

另外,如果你想知道为什么在这种情况下编译器不知道let x = 5; 没有指定类型应该分配i32 (默认的整数类型)并使用它的count_ones实现,它只是不是编译阶段 - 在解析方法和函数名称后分配默认类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM