Created
January 14, 2019 08:01
-
-
Save rust-play/eb6c3febd7a0a13084d02d972f38bed6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(result_map_or_else)] | |
extern crate serde; // 1.0.84 | |
extern crate serde_derive; // 1.0.84 | |
extern crate serde_json; // 1.0.34 | |
use serde::Serialize; | |
#[derive(Debug, Serialize)] | |
#[serde(tag = "status", content = "result")] | |
enum MyJsonResult<T, E> | |
where | |
T: Serialize, | |
E: Serialize, | |
{ | |
Success(T), | |
Error(E), | |
} | |
#[derive(Debug, Serialize)] | |
struct Post { | |
pub author: String, | |
pub content: String, | |
} | |
#[derive(Debug, Serialize)] | |
enum JsonStatus { | |
Success, | |
Error, | |
} | |
fn main() { | |
let result: Result<Vec<Post>, &'static str> = Ok(vec![Post { | |
author: "fuck".to_string(), | |
content: "you".to_string(), | |
}]); | |
let result = result.map_or_else( | |
|item| MyJsonResult::Error(item), | |
|item| MyJsonResult::Success(item), | |
); | |
println!("{}", serde_json::to_string_pretty(&result).unwrap()); | |
let result: Result<Vec<Post>, &'static str> = Err("posts not found"); | |
let result = result.map_or_else( | |
|item| MyJsonResult::Error(item), | |
|item| MyJsonResult::Success(item), | |
); | |
println!("{}", serde_json::to_string_pretty(&result).unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment