Naming for constructors that are borrowing or copying

I have an Image type that can be constructed as either borrowing/referencing pixels (Image<'pixels>) or copying/owning them (Image<'static>)

How would you name functions that construct each kind of the image?

It could be new_owned() and new_borrowed(), or new_copy() (new_copied()?) and new_ref(). Perhaps one of them could be plain new, and the other have a different name.

Which does sound better? Is there a precedent in popular Rust libraries for this?

As a relative newcomer to the language, I might expect them to be . borrows() and .owns() but I haven't encountered anything like that in the few libraries I've used.

If constructing the borrowed version is cheap, it might be no overhead always going through Image<'a> first. Then that could be simply Image::from(&something) for creating the Image<'a>, and then one can chain a call for of an .owned() method or something like that to crate the Image<'static>?


And if the construction of Image<'static> from an owned container can be possible without copying everything, then I suppose that can be supported with another From implementation.

I would follow the style use by std's Cow type (which works similarly) and use Image::owned and Image::borrowed (or Image::new_owned and Image::new_borrowed)

(edit: oops, responded to the wrong person)

1 Like

I need extra arguments like width and height, so I can't use From/Into (I'm excluding cleverness with tuples).

Another idea: Image::new (owned) and Image::with_ref

Oh, I see. Maybe an fn new<'a, T>(data: T, height, width) -> Image<'a> where T: ImageData<'a> style method could still be nice. (ImageData could be a sealed trait.) Similar to the From approach, but a custom trait. Still, borrowed data gives borrowed image, owned data gives owned image; creating an owned image from borrowed data requires an extra method call for turning the image into owned.


I'm currently not aware of any precedent to compare to. Crates that I've seen like ndarray use separate types for owned and borrowed data, but I guess the ergonomics of unifying the two might be nice.

I went for new that takes Into<Box> and new_borrowed. Thanks for your input.

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.