Skip to content

feat: #[constructor(into)] syntax for automatic Into generics#551

Draft
gavincrawford wants to merge 2 commits into
JelteF:masterfrom
gavincrawford:constructor_into
Draft

feat: #[constructor(into)] syntax for automatic Into generics#551
gavincrawford wants to merge 2 commits into
JelteF:masterfrom
gavincrawford:constructor_into

Conversation

@gavincrawford
Copy link
Copy Markdown

@gavincrawford gavincrawford commented Jun 1, 2026

Resolves #541

Synopsis

The following pattern is common in many Rust projects/libraries as a way to expand what types constructors accept:

pub struct UserID(String);

impl UserID {
    pub fn new<S: Into<String>>(value: S) -> Self {
        Self(value.into())
    }
}

It would be convenient to be able to have a derived constructor that is capable of replicating this behavior for types that implement Into<T>.

Solution

This solution uses a new attribute, #[constructor(into)] (very subject to change) that allows users to designate specific fields to accept generic inputs. For example:

#[derive(Constructor)]
struct UserID {
    #[constructor(into)]
    id: String
}

will have a corresponding new implementation that accepts id: impl Into<String>.

One caveat of this feature is that Into::into() is non-constant, which means the new, derived constructor function can't be either. In this implementation, I chose to handle this conditionally-- if Into<T> fields are present, new is not constant; otherwise, it still is.

I haven't added docs/tests yet, because I think it'd be worth talking about exactly what we want this syntax to look like, and if this is a feature that is within the scope of what this crate is meant to provide.

Checklist

  • Documentation is updated (if required)
  • Tests are added/updated (if required)
  • CHANGELOG entry is added (if required)

@gavincrawford gavincrawford marked this pull request as draft June 1, 2026 16:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Converting Constructor

1 participant