所以在Rust中,我遇到的一个问题是类型推理能力,当涉及到值与引用时。例如,
fn main() {
let s1 = String::from("h1");
let s2 = &s1;
println!("string is {}", s1);
}
借用检查器允许这个编译,但我不知道为什么? s2
在这里是值还是被推断为对s1的引用?
在C ++中,通过引用初始化新值将创建一个副本,除非该变量被显式声明为引用:
#include <string>
int main(int argc, char const* argv[]) {
std::string s1("Hello");
std::string& s2 = s1; // reference
std::string s3 = s2; // copy
}
因此,在生锈中,我的问题是,类型推断是否也适用于参考值和价值情况?如果是,何时需要显式声明变量作为引用?
s2
的类型是&std::string::String
,更常见的表达为&String
。
s2
是以(只读)参考(s1
)的形式借用&
,并且当s1
在范围内时,将阻止s2
被写入(如果它是可变的)。
如果您想要求编译器显示特定绑定的类型,常见的习惯用法是使用let () = some_binding;
。编译器会给你一个错误,揭示some_binding
的类型。
我注意到编译器似乎通过省略领先的&
来“帮助”,所以当你对Rust感到满意时,我建议尝试使用错误类型调用虚函数,这会显示绑定的完整类型。在这里,编译器确实显示了调用参数的完整类型,您可以看到它是&String
。
关于明确声明声明的let
方面的类型,如在C ++(see 'AAA')中,Rust支持类似的东西:
let a: u32 = 42;
// equvialent
let b = 42_u32;
对于构造类型,类型将是类型构造函数返回的任何类型:
// seems somewhat redundant (since `String::new()` returns `String`)
// but is perfectly legal
let c: String = String::new("Hello, world!");
// equivalent
let d = String::new("Hello, world!");
因此,只要编译器可以从右侧明确地确定类型,就可以推断出let
的类型。
注意:const
绑定仍然必须使用类型规范:
// error: despite the explicit type declaration on the RHS, the type is still required
//const foo = 42_u32;
// since the type must be explicitly defined specifying again on the RHS is redundant
// (but legal):
const foo: u32 = 42_u32;
// Rustic (idiomatic) for `const`
const bar: u32 = 42;