相关疑难解决方法(0)

当未声明为变量的变量被修改时,为什么编译器不报告错误?

我安装了Rust 1.13并试过:

fn main() {
    let x: u32;
    x = 10; // no error?
}
Run Code Online (Sandbox Code Playgroud)

当我编译这个文件时有一些警告,但是没有错误.因为我不声明x作为mut,不应该x = 10;导致错误?

variables syntax compilation mutable rust

8
推荐指数
2
解决办法
194
查看次数

我如何制作格式!从条件表达式返回 &str?

我遇到了这个问题format!,据我所知,在一个没有锚定到任何东西的模式中创建一个临时值。

let x = 42;
let category = match x {
    0...9 => "Between 0 and 9",
    number @ 10 => format!("It's a {}!", number).as_str(),
    _ if x < 0 => "Negative",
    _ => "Something else",
};

println!("{}", category);
Run Code Online (Sandbox Code Playgroud)

在这段代码中, 的类型category是 a &str,它通过返回一个像 的文字来满足"Between 0 and 9"。如果我想使用 将匹配的值格式化为切片as_str(),则会出现错误:

let x = 42;
let category = match x {
    0...9 => "Between 0 and 9",
    number @ 10 => format!("It's a {}!", …
Run Code Online (Sandbox Code Playgroud)

string scope temporary lifetime rust

8
推荐指数
1
解决办法
2502
查看次数

标签 统计

rust ×2

compilation ×1

lifetime ×1

mutable ×1

scope ×1

string ×1

syntax ×1

temporary ×1

variables ×1