hcl::ser

Function block

Source
pub fn block<T, S>(value: T, serializer: S) -> Result<S::Ok, S::Error>
where T: Serialize, S: Serializer,
Expand description

Hints the Serializer to serialize T as an HCL block.

This function is intended to be used in the #[serde(serialize_with)] attribute and wraps T with a Block<T>.

See the type-level documentation of Block<T> for more.

§Example

use serde::Serialize;

#[derive(Serialize)]
struct Config {
    #[serde(serialize_with = "hcl::ser::block")]
    user: Vec<User>,
}

#[derive(Serialize)]
struct User {
    name: String,
    email: String,
}

let config = Config {
    user: vec![
        User {
            name: "john".into(),
            email: "johndoe@example.com".into(),
        },
        User {
            name: "jane".into(),
            email: "janedoe@example.com".into(),
        },
    ],
};

let expected = r#"
user {
  name = "john"
  email = "johndoe@example.com"
}

user {
  name = "jane"
  email = "janedoe@example.com"
}
"#.trim_start();

assert_eq!(hcl::to_string(&config)?, expected);

§Errors

Serialization fails if the type’s shape makes it impossible to represent it as an HCL block with two labels.