Skip to content

Instantly share code, notes, and snippets.

@berkus
Forked from rust-play/playground.rs
Created January 14, 2019 08:02
Show Gist options
  • Save berkus/cc3ee25e848ab83e0598c8ae55b49d2d to your computer and use it in GitHub Desktop.
Save berkus/cc3ee25e848ab83e0598c8ae55b49d2d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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());
}
@berkus
Copy link
Author

berkus commented Jan 14, 2019

Serde serialize structure like:

{
  "status": "Success",
  "result": [
    {
      "author": "fuck",
      "content": "you"
    }
  ]
}

or

{
  "status": "Error",
  "result": "posts not found"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment