Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add default for structs to attr-default page #84

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion _src/attr-default.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Default value for a field

!PLAYGROUND 26df8969cb9df94a7d4a0443dcfb712f
!PLAYGROUND 7683f076daaf4a4f7d043bcb645c5442
```rust
#[macro_use]
extern crate serde_derive;
Expand All @@ -9,7 +9,12 @@ extern crate serde;
extern crate serde_json;

#[derive(Deserialize, Debug)]
#[serde(default)]
struct Request {
// Use the encapsulating structs default value if "method" is not
// included in the input
method: Method,

// Use the result of a function as the default if "resource" is
// not included in the input.
#[serde(default = "default_resource")]
Expand All @@ -26,6 +31,20 @@ struct Request {
priority: Priority,
}

impl Default for Request {
fn default() -> Self {
Request {
timeout: Timeout(0),
priority: Priority::Normal,
resource: "/resource".to_string(),
method: Method::Get
}
}
}

#[derive(Deserialize, Debug)]
enum Method { Post, Get, Update, Delete }

fn default_resource() -> String {
"/".to_string()
}
Expand Down