相关疑难解决方法(0)

println!借用或拥有变量?

我对借贷和所有权感到困惑.在Rust 文档中有关引用和借用的内容

let mut x = 5;
{
    let y = &mut x;
    *y += 1;
}
println!("{}", x);
Run Code Online (Sandbox Code Playgroud)

他们说

println!可以借x.

我很困惑.如果println!借入x,为什么它通过x&x

我尝试在下面运行此代码

fn main() {
    let mut x = 5;
    {
        let y = &mut x;
        *y += 1;
    }
    println!("{}", &x);
}
Run Code Online (Sandbox Code Playgroud)

除了传递&x给代码之外,这段代码与上面的代码相同println!.它将'6'打印到控制台,这是正确的,与第一个代码的结果相同.

ownership rust

39
推荐指数
1
解决办法
2219
查看次数

如何在Rust中打印变量并让它显示有关该变量的所有内容,例如Ruby的.inspect?

use std::collections::HashMap;

fn main() {
    let mut hash = HashMap::new();
    hash.insert("Daniel", "798-1364");
    println!("{}", hash);
}
Run Code Online (Sandbox Code Playgroud)

不会编译错误

特征绑定std :: collections :: HashMap <&str,&str>:std :: fmt ::显示不满意

有没有办法说出类似的话:

error[E0277]: `std::collections::HashMap<&str, &str>` doesn't implement `std::fmt::Display`
 --> src/main.rs:6:20
  |
6 |     println!("{}", hash);
  |                    ^^^^ `std::collections::HashMap<&str, &str>` cannot be formatted with the default formatter
  |
Run Code Online (Sandbox Code Playgroud)

打印出来:

println!("{}", hash.inspect());
Run Code Online (Sandbox Code Playgroud)

debugging println rust

10
推荐指数
2
解决办法
5809
查看次数

我应该实现Display或ToString将类型呈现为字符串吗?

我有一种类型Foo,我希望能够作为字符串显示给最终用户,通过实现Display或实现这样做是否更惯用ToString

如果Display是要走的路,我怎么会最终得到一个String?我怀疑我需要使用write!,但我不完全确定如何.

string rust

9
推荐指数
1
解决办法
1988
查看次数

println的格式样式有什么区别?

我很遗憾地问这么简单的问题......前一天,我开始学习Rust并尝试了这个println!方法.

fn main() {
  println!("Hello {}!", "world");
}
-> Hello world!
Run Code Online (Sandbox Code Playgroud)

然后,我找到了其他格式样式:{}, {:}, {:?}, {?},...

我知道{}相反String,但我不理解其他格式风格.这些款式如何相互不同?我认为{:?}是数组或向量.这是对的吗?

请用示例代码解释这些格式样式:(

rust

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

标签 统计

rust ×4

debugging ×1

ownership ×1

println ×1

string ×1