我正在学习/试验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) 我无法理解盒装特征的价值是如何形成的.请考虑以下代码:
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>正在执行. …
我正在学习 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) 有据可查,[T; n]可以强制到[T]. 以下代码也是格式良好的:
fn test(){
let _a: &[i32] = &[1, 2, 3];
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们将&[T; n]强制转换为&[T].
是不是对于所有类型T,U如果T被强制为Uthen&T被强制为&U?
它没有记录在参考文献中(至少是明确的)。