Skip to main content

Module option

Module option 

Source
Expand description

Encode an Option<T> through Display and decode it through FromStr.

The value is encoded as an optional string, so None is encoded the same way as it is for any other Option<T>.

§Examples

use std::net::Ipv4Addr;

use musli::{Decode, Encode};

#[derive(Debug, PartialEq, Encode, Decode)]
struct Host {
    #[musli(with = musli::display::option)]
    gateway: Option<Ipv4Addr>,
}

let host = Host { gateway: Some(Ipv4Addr::new(10, 0, 0, 1)) };
let json = musli::json::to_string(&host)?;
assert_eq!(json, r#"{"gateway":"10.0.0.1"}"#);
assert_eq!(musli::json::from_str::<Host>(&json)?, host);

Functions§

decode
Decode an optional string and parse it through FromStr.
encode
Encode value as an optional string through Display.