How do I cast a structure to Vec<(&str, String)>?

Summary

I would like to cast the structure below to Vec<(&str, String)>, but I don't know how.

struct Post {
    user_id: i32,
    id: i32,
    title: String,
}

Do I need some other crate?

The format I want to output

I want to output the same results as generated by the code below.

vec![
        ("user_id", 1.to_string),
        ("id", 1.to_string),
        ("tile", "This is title".to_string()),
    ]

I checked past topics but could not find any applicable ones.
Any help would be greatly appreciated.

I don't think there is a ready-to-use method for that, but you could simply define one:

impl Post {
    fn fields(&self) -> Vec<(&'static str, String)> {
        vec![
            ("user_id", self.user_id.to_string()),
            ("id", self.id.to_string()),
            ("title", self.title.to_string()),
        ]
    }
}

Note that you should use the 'static lifetime for the field name.

4 Likes

Iā€™d additionally recommend to use HashMap<T0, T1> instead of Vec<(T0, T1)>

4 Likes

Appreciate the advice.

Thanks to your help, it went well.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.