rust - Rust 中引用与值的显式注释

标签 rust

所以在 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
}

所以在 Rust 中,我的问题是,类型推断是否也适用于引用与值的情况?如果是这样,什么时候需要显式声明变量为引用?

最佳答案

我是什么类型的?

s2 的类型是&std::string::String,通常表示为&String

s2 以(只读)引用(&)的形式借用 s1,并且会阻止 s1 被写入(如果它是可变的)而 s2 在范围内。

我以后如何自行决定?

Sample code on Playground

如果您想要求编译器揭示特定绑定(bind)的类型,一个常见的习惯用法是使用 let () = some_binding;。编译器会给你一个错误,显示 some_binding 的类型。

我注意到编译器似乎通过省略前导的 & 来“帮助”,所以当您熟悉 Rust 时,我建议尝试调用错误类型的虚拟函数,这会揭示绑定(bind)的完整类型。在这里,编译器确实揭示了调用参数的完整类型,您可以看到它是 &String

显式声明类型(解决 OP 的评论):

关于在声明的 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 绑定(bind)的类型规范仍然是强制性的:

// 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;

关于rust - Rust 中引用与值的显式注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907873/

相关文章:

attributes - 是否可以将函数设置为仅在发布构建期间内联?

rust - 如何在 Rust 中将字符串转换为整数?

import - 包括一个内部模块产生 "maybe a missing crate ` 模块 2`"

macros - 宏观规则!宏采用字符串文字 "...",扩展为 "..."和 b"..."

rust - 是否可以在类型别名上实现方法?

parsing - 使用 match 查看 stdin

rust - 如何共享堆分配的特征对象?

regex - Visual Studio Code 任务正则表达式未捕获构建错误输出

rust - 为什么结构中的 Box<T> 为 "explicit lifetime bound required"?

rust - 了解 rust `Rc<RefCell<_>>`