Trait rustc_serialize::Encodable
source · 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§
Object Safety§
This trait is not object safe.