Just look at the simple code:
use redis::{FromRedisValue, Value, RedisResult, Commands, from_redis_value, ErrorKind};
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct Uids(Vec<u16>);
#[derive(Deserialize, Debug)]
pub struct Ages(Vec<u8>);
impl FromRedisValue for Uids {
fn from_redis_value(v: &Value) -> RedisResult<Self> {
let json_str: String = from_redis_value(v)?;
let result: Self = match serde_json::from_str::<Self>(&json_str) {
Ok(v) => v,
Err(_err) => return Err((ErrorKind::TypeError, "Parse to JSON Failed").into())
};
Ok(result)
}
}
impl FromRedisValue for Ages {
fn from_redis_value(v: &Value) -> RedisResult<Self> {
let json_str: String = from_redis_value(v)?;
let result: Self = match serde_json::from_str::<Self>(&json_str) {
Ok(v) => v,
Err(_err) => return Err((ErrorKind::TypeError, "Parse to JSON Failed").into())
};
Ok(result)
}
}
pub fn get_value<T>() -> RedisResult<Option<T>> where
T: FromRedisValue {
let client = redis::Client::open("redis://127.0.0.1:6379/").unwrap();
let mut con = client.get_connection().unwrap();
con.get("json")
}
fn main() {
match get_value::<Uids>() {
Ok(redis_value) => match redis_value {
Some(result) => println!("{:?}", result),
None => println!("No value in Redis"),
},
Err(err) => {
println!("Error: {}", err);
}
}
match get_value::<Ages>() {
Ok(redis_value) => match redis_value {
Some(result) => println!("{:?}", result),
None => println!("No value in Redis"),
},
Err(err) => {
println!("Error: {}", err);
}
}
}
The value of key "json" is "[65, 28]" in Redis, Running then will print
Compiling rust-trait-generics v0.1.0 (D:\code\rust-trait-generics)
Finished dev [unoptimized + debuginfo] target(s) in 1.17s
Running `target\debug\rust-trait-generics.exe`
Uids([65, 28])
Ages([65, 28])
And now, you can see that the struct Uids and Ages all the structs need to impl a FromRedisValue trait, but there is a duplicate code there
impl FromRedisValue for Uids {
fn from_redis_value(v: &Value) -> RedisResult<Self> {
let json_str: String = from_redis_value(v)?;
let result: Self = match serde_json::from_str::<Self>(&json_str) {
Ok(v) => v,
Err(_err) => return Err((ErrorKind::TypeError, "Parse to JSON Failed").into())
};
Ok(result)
}
}
impl FromRedisValue for Ages {
fn from_redis_value(v: &Value) -> RedisResult<Self> {
let json_str: String = from_redis_value(v)?;
let result: Self = match serde_json::from_str::<Self>(&json_str) {
Ok(v) => v,
Err(_err) => return Err((ErrorKind::TypeError, "Parse to JSON Failed").into())
};
Ok(result)
}
}
So I felt something I was wrong on it. How can I to doing like that
impl FromRedisValue for Uids, Ages {
fn from_redis_value(v: &Value) -> RedisResult<Self> {
let json_str: String = from_redis_value(v)?;
let result: Self = match serde_json::from_str::<Self>(&json_str) {
Ok(v) => v,
Err(_err) => return Err((ErrorKind::TypeError, "Parse to JSON Failed").into())
};
Ok(result)
}
}
Help me to do that, please, thank you!