Best practice for handling READONLY field in Rust? #5770
-
Assume I have a table that contains a #[derive(Debug, Deserialize, Serialize)]
struct ForWriting {
name: String,
}
#[derive(Debug, Deserialize)]
struct ForReading {
name: String,
order: i64,
} Or is there another way to use a single struct for both? I tried using |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 4 replies
-
Yeah using two #[derive(Deserialize)]
pub struct User {
email: email_address::EmailAddress,
#[serde(rename = "password")]
hashed_password: Box<str>,
other_info: OtherInfo,
}
mod sign_up{
pub async fn sign_up_user(db: ..., user: SignUpUser) { ...}
#[derive(Serialize)]
pub struct SignUpUser {
email: String,
#[serde(rename = "password")]
plaintext_password: String,
}
} Although, relying on the pub mod writing{
#[derive(Debug, Serialize)]
pub struct ForWriting {
name: String,
order: i64,
}
const ORDER_DEFAULT: i64 = 69;
impl ForWriting{
pub fn new(name: String) { ForWriting { name, order: ORDER_DEFAULT } }
pub fn with_order(mut self, order: i64) -> Self { self.order = order; self }
}
} That way when your consuming your own code, due to rust privacy restrictions (module boundaries), your guarenteed to provide the default but also have the option of changing it. #[derive(Debug, Serialize)]
pub struct ForWriting {
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
order: Option<i64>,
} |
Beta Was this translation helpful? Give feedback.
-
Interesting. I think I chose a bad example. Another issue related to this one is that I have a few fields that will only ever be set and updated database-side (e.g. |
Beta Was this translation helpful? Give feedback.
-
Yes, you can’t have your cake of memory safety and type safety and in one type be able to express two distinct serde/data models |
Beta Was this translation helpful? Give feedback.
-
What brought up this quesiton was a weird interaction I had with SurrealDB using a struct Combo {
value: String,
version: Option<i64>,
} When I used the Rust SDK to create a record, the schema did not automatically populate the CREATE combo
SET value = "example",
version = NONE It seemed that by specifying |
Beta Was this translation helpful? Give feedback.
You misunderstand, read the docs on the VALUE clause, it’s used in the DEFINE FIELD, e.g. DEFINE FIELD created_at VALUE time::now()