pub trait Serialize {
// Required method
fn serialize<S>(
&self,
name: &str,
serializer: &mut S,
) -> Result<(), S::Error>
where S: Serializer;
}Expand description
Trait for types that can be serialized.
This trait should be implemented (or derived) for any type that needs to be serialized. The implementation defines how the type should be written to a serializer.
§Derive Macro
The easiest way to implement this trait is using the derive macro (requires derive feature):
ⓘ
use osal_rs_serde::Serialize;
#[derive(Serialize)]
struct Config {
id: u32,
enabled: bool,
timeout: Option<u16>,
}§Manual Implementation
For custom serialization logic or types not supported by the derive macro:
ⓘ
use osal_rs_serde::{Serialize, Serializer};
struct Point {
x: i32,
y: i32,
}
impl Serialize for Point {
fn serialize<S: Serializer>(&self, serializer: &mut S) -> core::result::Result<(), S::Error> {
serializer.serialize_i32("x", self.x)?;
serializer.serialize_i32("y", self.y)?;
Ok(())
}
}§Built-in Implementations
This trait is already implemented for:
- All primitive types (bool, u8-u128, i8-i128, f32, f64)
- Arrays
[T; N]where T: Serialize - Tuples (T1, T2) and (T1, T2, T3) where all T: Serialize
Option<T>where T: SerializeVec<T>where T: Serialize (requiresalloc)Stringand&str(requiresallocfor String)
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".