From 20f43f7f8a83ffc1a43c1af3bad0e972d620c17b Mon Sep 17 00:00:00 2001 From: Stefan Lau Date: Mon, 5 Nov 2018 18:28:23 +0100 Subject: [PATCH] Add default for structs to attr-default page --- _src/attr-default.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/_src/attr-default.md b/_src/attr-default.md index 2c43c361..0d4d6b2f 100644 --- a/_src/attr-default.md +++ b/_src/attr-default.md @@ -1,6 +1,6 @@ # Default value for a field -!PLAYGROUND 26df8969cb9df94a7d4a0443dcfb712f +!PLAYGROUND 7683f076daaf4a4f7d043bcb645c5442 ```rust #[macro_use] extern crate serde_derive; @@ -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")] @@ -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() }