相关疑难解决方法(0)

什么是Rust的确切自动解除引用规则?

我正在学习/试验Rust,在我用这种语言找到的所有优雅中,有一个让我感到困惑并且看起来完全不合适的特点.

在进行方法调用时,Rust会自动取消引用指针.我做了一些测试来确定确切的行为:

struct X { val: i32 }
impl std::ops::Deref for X {
    type Target = i32;
    fn deref(&self) -> &i32 { &self.val }
}

trait M { fn m(self); }
impl M for i32   { fn m(self) { println!("i32::m()");  } }
impl M for X     { fn m(self) { println!("X::m()");    } }
impl M for &X    { fn m(self) { println!("&X::m()");   } }
impl M for &&X   { fn m(self) { println!("&&X::m()");  } }
impl M for &&&X  { …
Run Code Online (Sandbox Code Playgroud)

reference dereference formal-semantics rust

152
推荐指数
2
解决办法
2万
查看次数

盒装特征创造背后的机制如何运作?

我无法理解盒装特征的价值是如何形成的.请考虑以下代码:

trait Fooer {
    fn foo(&self);
}

impl Fooer for i32 {
    fn foo(&self) { println!("Fooer on i32!"); }
}

fn main() {
    let a = Box::new(32);                    // works, creates a Box<i32>
    let b = Box::<i32>::new(32);             // works, creates a Box<i32>
    let c = Box::<Fooer>::new(32);           // doesn't work
    let d: Box<Fooer> = Box::new(32);        // works, creates a Box<Fooer>
    let e: Box<Fooer> = Box::<i32>::new(32); // works, creates a Box<Fooer>
}
Run Code Online (Sandbox Code Playgroud)

显然,变体a和b是微不足道的.但是,变量c没有,可能是因为该new函数只采用相同类型的值,而不是这种情况Fooer != i32.变种d和e的工作,这让我怀疑某种自动转换从Box<i32>Box<Fooer>正在执行. …

polymorphism boxing traits representation rust

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

在 Rust 中克隆一个 Rc 指针到一个特征对象上?

我正在学习 Rust,不明白为什么以下内容不起作用。我想我们无法在特征对象上克隆 Rc 指针?我如何将这样的引用传递给仅由特征定义的函数,如尝试的那样some_function

use std::rc::Rc;

trait SomeTrait {}
struct SomeThing {}
impl SomeTrait for SomeThing {}

fn some_function(s: Rc<dyn SomeTrait>) {}
fn another_function(s: &Rc<dyn SomeTrait>) {}

fn main() {
    let s = Rc::new(SomeThing{});

    // This doesnt work
    some_function(Rc::clone(&s));

    // I could do this
    some_function(s);

    // But then I could not do this
    some_function(s);
    
    // For that matter, neither can I do this
    another_function(&s);
}
Run Code Online (Sandbox Code Playgroud)

smart-pointers traits rust trait-objects

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

对于所有类型的`T`,`U`,如果`T` 被强制转换为`U` 那么`&amp;T` 被强制转换为`&amp;U`,这是真的吗?

据可查[T; n]可以强制到[T]. 以下代码也是格式良好的

fn test(){
    let _a: &[i32] = &[1, 2, 3];
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们将&[T; n]强制转换为&[T].

是不是对于所有类型TU如果T被强制为Uthen&T被强制为&U

它没有记录在参考文献中(至少是明确的)。

language-lawyer type-coercion rust

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