Skip to content

[Feature] Add an as_ref conversion #355

@JP-Ellis

Description

@JP-Ellis

Background

The into conversion is quite powerful, and the pros and cons of it are quite clearly outlined in the docs.

One of the main cons is that it can result is fairly expensive conversions to take place implicitly.

The AsRef trait is specifically designed to perform cheap conversions.

One very common example I see is:

fn inspect_file(file: impl AsRef<Path>) { ... }

// which can be used

inspect_file("hello.rs")

The &str is cheaply converted into a &Path and handled internally.

Proposal

I think it would be good if Bon could allow marking certain types to support AsRef, in much the same way that into is implemented:

#[derive(Builder)]
struct Example {
    #[builder(into)] 
    name: String,

	#[builder(as_ref)]
    location: &Path,
}

The name would be as_ref as the snake_case equivalent of the trait AsRef.

Related Work

A note for the community from the maintainers

Please vote on this issue by adding a 👍 reaction to help the maintainers with prioritizing it. You may add a comment describing your real use case related to this issue for us to better understand the problem domain.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions