相关疑难解决方法(0)

了解Vec <T>的Debug实现

试图Debug为自定义类型实现特性我偶然发现了它的实现Vec<T>.我很难理解它是如何工作的.

实现如下:

impl<T: fmt::Debug> fmt::Debug for Vec<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,它调用了fmt其他类型的实现.我无法理解的是它是什么类型.我试图在另一个问题的帮助下弄清楚它,并在实现中Debug搜索看起来合适的东西(可能是类似的东西&[T]),但没有成功.

&**self在这种情况下,确切含义是什么?Debug正在调用什么实现?

reference dereference rust

5
推荐指数
1
解决办法
143
查看次数

什么和*结合在一起做Rust?

我正在阅读关于Strings 的书籍部分,并发现他们正在&*结合使用来转换一段文字.它的内容如下:

use std::net::TcpStream;

TcpStream::connect("192.168.0.1:3000"); // Parameter is of type &str.

let addr_string = "192.168.0.1:3000".to_string();
TcpStream::connect(&*addr_string); // Convert `addr_string` to &str.
Run Code Online (Sandbox Code Playgroud)

换句话说,他们说他们正在将a转换String成a &str.但为什么使用上述两种标志进行转换呢?如果不使用其他方法吗?&我们是不是意味着它的参考,然后使用它*来取消引用它?

rust

5
推荐指数
2
解决办法
184
查看次数

添加引用和数字值时理解(自动?)Deref /强制

如何理解下面这段代码?我是Rust的新手,但有C/Haskell背景和一点点C++.我能找到的唯一参考是减轻强制.

fn main() {
    let xs: [u32; 4] = [0, 1, 2, 3];
    let mut i: u32 = 0;
    for x in xs.iter() {
        if i > *x {     // It looks x is an iterator. Understood.            
            i = i + x;  // no error. (coerced)
                        //Quote: "Rust will do this as many times
                        //       as possible until the types match."
            i = i + *x; // no error (explicit deref)
            i += x;     // error about u32/&u32 …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
624
查看次数

Rust中星号符号的用法是什么?

我是Rust的新手,我不理解以下代码:

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

Rust网站的说明:

您还会注意到,我们增加了一个星号(*前面)y,使得它*y,这是因为y是一个&mut参考。您还需要使用astrisks [sic]访问引用的内容。

如果*y是参考,以下代码为何起作用

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

我知道我没有在这里修改值,但是有什么区别,为什么y += 1;不起作用?

rust

4
推荐指数
1
解决办法
2206
查看次数

带有多个&符号的程序工作正常

以下程序工作正常:

pub fn foo(_v: &str) -> bool {
    false
}

fn main() {
    let f = "hello world";
    println!("{}", foo(&&&&f)); // note the number of & here
}
Run Code Online (Sandbox Code Playgroud)

事实上,它适用于传递任意数量的&. 我应该如何解释正在发生的事情?

我的锈版:

$ rustc --version
rustc 1.32.0-nightly (13dab66a6 2018-11-05)
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
2
解决办法
319
查看次数

当使用 ReadBytesExt 从字节切片中读取整数时,为什么会收到错误“不满足特征边界”?

以下 Rust 代码无法编译。

extern create byteorder;
use byetorder::{LittleEndian, ReadBytesExt};

fn main() {                                                                          
    let buf: [u8; 12] = [                                                                     
        0x00, 0x42, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x30,               
    ];
    let id = &buf[0..1].read_u16::<LittleEndian>();              }
Run Code Online (Sandbox Code Playgroud)

来自编译器的消息:

extern create byteorder;
use byetorder::{LittleEndian, ReadBytesExt};

fn main() {                                                                          
    let buf: [u8; 12] = [                                                                     
        0x00, 0x42, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x30,               
    ];
    let id = &buf[0..1].read_u16::<LittleEndian>();              }
Run Code Online (Sandbox Code Playgroud)

u16Stack Overflow 上有非常相似的问题,我已经评论过,但我的问题与那些问题略有不同,因为我试图从切片中读取 a 。在实践中,我不确定为什么我的例子有本质上的不同,我确信我错过了一些明显的东西。

具体来说,我不清楚我所得到的与此处接受的答案中的内容有何显着不同:

如何将字节切片 (&[u8]) 的缓冲区转换为整数? …

arrays casting reference slice rust

4
推荐指数
1
解决办法
4723
查看次数

如何在 Rust 中解释对可变类型的不可变引用?

如果我的取消引用链中有任何不可变的引用,我似乎无法改变任何东西。一个样品:

fn main() {
    let mut x = 42;
    let y: &mut i32 = &mut x; // first layer
    let z: &&mut i32 = &y; // second layer
    **z = 100; // Attempt to change `x`, gives compiler error.

    println!("Value is: {}", z);
}
Run Code Online (Sandbox Code Playgroud)

我收到编译器错误:

fn main() {
    let mut x = 42;
    let y: &mut i32 = &mut x; // first layer
    let z: &&mut i32 = &y; // second layer
    **z = 100; // Attempt to …
Run Code Online (Sandbox Code Playgroud)

immutability mutability rust borrow-checker

4
推荐指数
1
解决办法
959
查看次数

互斥体可以尊重结构但不能尊重原语

以下代码中结构体Counter包装了u32. 我正在使用Arc包装并Mutex允许对值进行安全和共享的访问。我省略了线程代码以提供一个简单的示例:

use std::sync::{Arc, Mutex};

fn main() {
    #[derive(Debug)]
    struct Counter {
        count: u32,
    }

    let counter = Arc::new(Mutex::new(Counter { count: 0 }));

    for _ in 0..10 {
        let mut c_int = counter.lock().unwrap();
        c_int.count += 1;
    }

    println!("{:?}", counter.lock().unwrap());
}
Run Code Online (Sandbox Code Playgroud)

这里counter.lock().unwrap()能够透明地锁定互斥锁并解开结果,我不需要取消引用Arc. 还c_int透明地取消对作品的引用。

考虑以下代码,其中Counter替换为u32

use std::sync::{Arc, Mutex};

fn main() {
    let counter = Arc::new(Mutex::new(32));

    for _ in 0..10 {
        let mut c_int = …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
166
查看次数

将可变数组引用传递给也接受可变数组引用的函数时,为什么没有说明 &amp;mut?

我正在尝试为 i32 数组实现快速排序算法。我的问题是关于在将数组传递给函数时使用 &mut 的明显不一致。我的代码:

fn main() {
    let mut my_array = [5, 2, 8, 7];
    let high = my_array.len() - 1;
    quick_sort(&mut my_array, 0, high);
    print!("{:?}", my_array);
}

fn quick_sort(array: &mut [i32], low: usize, high: usize) {
    let pivot_idx = partition(array, low, high);

    // Separately sort elements before partition and after partition
    if pivot_idx > low {
        quick_sort(array, low, pivot_idx - 1);
    }
    if pivot_idx < high {
        quick_sort(array, pivot_idx + 1, high);
    }
}

fn partition(array: &mut [i32], …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
191
查看次数

如何匹配Arc内的选项?

对文档Arc<T>说:

Arc<T>自动解引用T(通过Deref特征),因此你可以调用T类型值的方法Arc<T>.

但有没有办法允许匹配Option-al类型?

这是一个简单的例子:

use std::sync::Arc;

fn main() {
    let foo: Arc<Option<String>> = Arc::new(Some("hello".to_string()));

    if foo.is_some() {
        println!("{}", foo.unwrap());
    }

    match foo {
        Some(hello) => {
            println!("{}", hello);
        }
        None => {}
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器错误是:

error[E0308]: mismatched types
  --> src/main.rs:11:9
   |
11 |         Some(hello) => {
   |         ^^^^^^^^^^^ expected struct `std::sync::Arc`, found enum `std::option::Option`
   |
   = note: expected type `std::sync::Arc<std::option::Option<std::string::String>>`
              found type `std::option::Option<_>`

error[E0308]: mismatched types …
Run Code Online (Sandbox Code Playgroud)

rust

3
推荐指数
1
解决办法
843
查看次数