我想继承结构,因为这些结构非常多余。只有id
不同:
#[derive(RustcDecodable, RustcEncodable)]
struct Movie {
id: i32,
title: String,
director: String,
releaseYear: i16,
genre: String,
}
#[derive(RustcDecodable, RustcEncodable)]
struct MovieInsert {
title: String,
director: String,
releaseYear: i16,
genre: String,
}
为什么要定义这些结构?当我从数据库中获取JSON数据时,我可以这样转换:
let movie = request.json_as::<MovieInsert>().unwrap();
当我通过POST插入JSON数据时,我可以这样转换。
let movies = conn.query("select id, title, releaseYear, director, genre from movie", &[]).unwrap();
let mut v: Vec<Movie> = vec![];
for row in &movies {
let movie = Movie {
id: row.get(0),
title: row.get(1),
releaseYear: row.get(2),
director: row.get(3),
genre: row.get(4),
};
v.push(movie);
}
let json_obj = json::encode(&v).unwrap();
你能否告诉我如何继承这种情况下的结构或其他良好做法?
这是我的插入代码。
如果我改变let movie = request.json_as::<MovieInsert>().unwrap();
到let movie = request.json_as::<Movie>().unwrap();
,
它失败了。
MovieInsert
至Movie
// insert
{
let conn = shared_connection.clone();
router.post("/api/movies", middleware! { |request, mut response|
let conn = conn.lock().unwrap();
let stmt = match conn.prepare("insert into movie (title, releaseYear, director, genre)
values ($1, $2, $3, $4)") {
Ok(stmt) => stmt,
Err(e) => {
return response.send(format!("Preparing query failed: {}", e));
}
};
let movie = request.json_as::<MovieInsert>().unwrap();
match stmt.execute(&[
&movie.title.to_string(),
&movie.releaseYear,
&movie.director.to_string(),
&movie.genre.to_string()
]) {
Ok(v) => println!("Inserting movie was Success."),
Err(e) => println!("Inserting movie failed. => {:?}", e),
};
});
}
尝试(经过验证的练习)
extern crate serialize;
use std::default::Default;
use serialize::{json, Decodable, Decoder};
#[deriving(Encodable, Decodable, Show)]
struct Movie {
_id: Option<i32>,
title: String,
director: String,
releaseYear: i16,
genre: String,
}
impl<S: Decoder<E>, E> Decodable<S, E> for Movie {
fn decode(decoder: &mut S) -> Result<Movie, E> {
decoder.read_struct("root", 0, |decoder| {
decoder.read_struct_field("data", 0, |decoder| {
Ok(Person{
age: try!(decoder.read_struct_field("_id", -1, |decoder| Decodable::decode(decoder)))
})
})
})
}
}
但是,Show
不存在``#[derive] for custom traits is not stable enough for use and is subject to change (see issue #29644)
src/main.rs:28 #[derive(Encodable, Decodable, Show)]
稍后我将deriving
更改为derive
。
warning: derive(Decodable) is deprecated in favor of derive(RustcDecodable)
src/main.rs:28 #[derive(Encodable, Decodable, Show)]
RustcDecodable
很好。可解码被淘汰了..
我刚刚更改了_id
#[derive(RustcDecodable, RustcEncodable)]
struct Movie {
_id: Option<i32>,
title: String,
director: String,
releaseYear: i16,
genre: String,
}