Construct struct with borrowed fields when struct is only ever borrowed

It would be quite useful if you could construct a struct with only borrowed data when the struct is only ever borrowed, despite the struct fields requiring owned data.

For example:

struct Foo {
    name: Vec<String>,

impl Foo {
    fn use_self_ref(&self) {
        // some long function I wouldn't want to duplicate...

fn do_something(name: &Vec<String>) {
    let foo = Foo {
        name: name.clone(), // Clone here is required...
    foo.use_self_ref(); // ... but not really used since `foo` is only ever used with `&self`.

It would be nice if I could pass the &Vec<String> directly to Foo since I only use foo as read only.

A summary of the rule would be something like:

If a struct is only ever referenced, then it can be constructed by references of each field.

I'm not sure what kind of issues this could cause if it was added to the language, and if it would over complicate things, but I feel it would be quite useful to avoid clones... especially for types which are defined in other crates.


The right forum to discuss this would be IRLO, as opposed to URLO, which is this forum.

1 Like

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.