-
Hello! Is there a recommended way to use a different method to use for constructing a property? This would be useful for interop with the Sorry if this is out of scope for the crate– but I would appreciate any pointers :) // title.rs
#[nutype(
sanitize(trim),
validate(with = validate_title, error = TitleError),
derive(
Clone, Debug, Display, PartialEq, Eq, PartialOrd, Ord, Deref, AsRef, Borrow, TryFrom, From
)
)]
pub struct Title(String);
mod tests {
#[cfg(test)]
use super::*;
#[test]
fn test_create_project_title() {
// 🤔 Will get compiler error if I use `new` constructor.
let title = Title::try_new("checking that this is a valid filename");
assert!(title.is_ok(), "A valid Title should be ok. Result: {:?}", title);
}
} // projects.rs
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, From)]
#[builder]
pub struct Project {
#[builder(try_new)] // 🤔 This syntax does not work obviously, but I'd love to use `try_new` instead of `new`.
title: Title,
}
mod tests {
#[cfg(test)]
use super::*;
#[test]
fn test_create_project() {
let project = Project::builder()
.title(String::from("test-title")) // 🤔 want to pass in String
.build();
assert_eq!(*project.title, "test-title");
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
lkdm
Sep 14, 2024
Replies: 1 comment 2 replies
-
Please ignore me, I found the article here which points out that I should be using a function builder. Here's an example of my code, in case its helpful to anyone: #[derive(Error, Debug, Clone, PartialEq)]
enum ProjectError {
#[error("Error")]
TitleError(#[from] TitleError)
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, From)]
pub struct Project {
title: Title,
}
#[bon]
impl Project {
#[builder]
fn new(title: &str) -> Result<Self, ProjectError> {
let title = Title::try_new(title.to_string())?;
Ok(Self {title})
}
}
mod tests {
#[cfg(test)]
use super::*;
#[test]
fn test_create_project() {
let project = Project::builder()
.title("test-title")
.build();
assert!(project.is_ok());
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
lkdm
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please ignore me, I found the article here which points out that I should be using a function builder.
Here's an example of my code, in case its helpful to anyone: