3

学习Rust:派生derive属性

 1 year ago
source link: https://www.jdon.com/62746
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

学习Rust:派生derive属性


当你有很多trait(接口)实现类型时,它很快就会变得乏味,并且可能会给你的代码增加很多复杂性。

struct Point {
    x: u64,
    y: u64,
}

impl Debug for Point {
    // ...
}

impl Display for Point {
    // ...
}

impl Something for Point {
    // ...
}

impl SomethingElse for Point {
    // ...
}

// ...

幸运的是,Rust 为我们提供了一些东西:derive 属性
通过使用该derive属性,我们实际上将我们的类型提供给一个Derive 宏,它是一种过程宏

他们将代码作为输入(在本例中为我们的类型),并在编译时创建更多代码作为输出。

这对于数据反序列化特别有用:只需实现 crate 中的 SerializeDeserialize特征,我们就可以将我们的类型序列化和反序列化为许多数据格式:JSONYAMLTOML , BSON等等...

use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Point {
    x: u64,
    y: u64,
}

不费吹灰之力,我们就为我们的结构Point实现了Debug、Clone、Serialize和Deserialize的trait。

需要注意的是,您的结构的所有子字段都需要实现这些trait。

use serde::{Serialize, Deserialize};

// 你不能这么做
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Point<T> {
    x: T,
    y: T,
}

// 你需要这么做:
use serde::{Serialize, Deserialize};
use core::fmt::Debug; // Import the Debug trait

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Point<T: Debug + Clone + Serialize + Deserialize> {
    x: T,
    y: T,
}

 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK