pub trait Encodable {
// Required method
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
}
Expand description
Trait for serializing a type.
This can be implemented for custom data types to allow them to be encoded
with Encoder
implementations. Most of Rust’s built-in or standard data
types (like i32
and Vec<T>
) have Encodable
implementations provided by
this module.
Note that, in general, you should let the compiler implement this for you by
using the derive(RustcEncodable)
attribute.
§Examples
extern crate rustc_serialize;
#[derive(RustcEncodable)]
struct Point {
x: i32,
y: i32,
}
This generates code equivalent to:
extern crate rustc_serialize;
use rustc_serialize::Encodable;
use rustc_serialize::Encoder;
struct Point {
x: i32,
y: i32,
}
impl Encodable for Point {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("Point", 2, |s| {
try!(s.emit_struct_field("x", 0, |s| {
s.emit_i32(self.x)
}));
try!(s.emit_struct_field("y", 1, |s| {
s.emit_i32(self.y)
}));
Ok(())
})
}
}
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.