Skip to content

Commit

Permalink
feat: add rust serde example
Browse files Browse the repository at this point in the history
  • Loading branch information
yifanwww committed Sep 17, 2023
1 parent ca77fb5 commit 8f815b8
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ node_modules

/lib
/lib-commonjs
/rust/target

# ----------------------------------------------------------------------------------------------------------------- Test

Expand Down
89 changes: 89 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0.107"
5 changes: 5 additions & 0 deletions rust/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod serde;

fn main() {
println!("Hello, world!");
}
30 changes: 30 additions & 0 deletions rust/src/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#[cfg(test)]
mod tests {
#[test]
fn it_result_to_json() -> serde_json::Result<()> {
let result1: Result<i32, &str> = Ok(1);
let result2: Result<i32, &str> = Err("Some error message");

let json1 = serde_json::to_string(&result1)?;
let json2 = serde_json::to_string(&result2)?;

assert_eq!(json1.as_str(), "{\"Ok\":1}");
assert_eq!(json2.as_str(), "{\"Err\":\"Some error message\"}");

Ok(())
}

#[test]
fn it_result_from_json() -> serde_json::Result<()> {
let str1 = "{\"Ok\":1}";
let str2 = "{\"Err\":\"Some error message\"}";

let result1: Result<i32, &str> = serde_json::from_str(str1)?;
let result2: Result<i32, &str> = serde_json::from_str(str2)?;

assert_eq!(result1, Ok(1));
assert_eq!(result2, Err("Some error message"));

Ok(())
}
}

0 comments on commit 8f815b8

Please sign in to comment.