Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 适用于所有T&;T、 &;mut T、[T]、&;[T] ,*mut T_Rust - Fatal编程技术网

Rust 适用于所有T&;T、 &;mut T、[T]、&;[T] ,*mut T

Rust 适用于所有T&;T、 &;mut T、[T]、&;[T] ,*mut T,rust,Rust,考虑以下代码: pub trait Hello { fn hello(&self); } impl Hello for Any { fn hello(&self) { println!("Hello!!!!!"); } } 我记得在某处看到Rust中有一个新功能,它允许您实现一个可直接访问所有对象的功能,如下所示: let foo = 0 as u8; foo.hello(); 不幸的是,我一直没能找到它。实际上是否有一个全局/通用的

考虑以下代码:

pub trait Hello {
    fn hello(&self);
}

impl Hello for Any {
    fn hello(&self) {
        println!("Hello!!!!!");
    }
}
我记得在某处看到Rust中有一个新功能,它允许您实现一个可直接访问所有对象的功能,如下所示:

let foo = 0 as u8;
foo.hello();

不幸的是,我一直没能找到它。实际上是否有一个全局/通用的“实现者”?

好吧,您可以对您的特性进行通用实现:

pub trait Hello {
    fn hello(&self);
}

impl<T> Hello for T {
    fn hello(&self) {
        println!("Hello!!!!!");
    }
}

fn main() {
    let foo = 0 as u8;
    foo.hello();
    let bar = "world!".to_string();
    bar.hello();
}
你好{ fn你好(&self); } 为T{ fn你好(&self){ println!(“你好!!!!!!!”); } } fn main(){ 设foo=0为u8; 喂; 让bar=“world!”.to_string(); bar.hello(); }
请注意,Rust目前不允许泛型的专门化(尽管它上有一个特殊的定义),因此您的trait实现必须像任何T一样工作。

好的,您可以对trait进行泛型实现:

pub trait Hello {
    fn hello(&self);
}

impl<T> Hello for T {
    fn hello(&self) {
        println!("Hello!!!!!");
    }
}

fn main() {
    let foo = 0 as u8;
    foo.hello();
    let bar = "world!".to_string();
    bar.hello();
}
你好{ fn你好(&self); } 为T{ fn你好(&self){ println!(“你好!!!!!!!”); } } fn main(){ 设foo=0为u8; 喂; 让bar=“world!”.to_string(); bar.hello(); }
请注意,Rust目前不允许泛型的专门化(尽管它上有一个特殊的定义),因此您的trait实现必须像任何T一样工作。

请注意,
impl Hello for any
实际上意味着
impl Hello for dyn any
,也就是说,它为
Any
trait的trait对象实现
Hello
trait。如果要对对象调用此函数,首先需要将其强制转换为trait对象,如
(&foo as&dyn Any)。hello()
。注意
impl hello for Any
实际上意味着
impl hello for dyn Any
,即它为
Any
trait的trait对象实现
hello
trait。如果要在对象上调用此函数,首先需要将其强制转换为trait对象,如
(&foo as&dyn Any).hello()