Rust API Design: When to Use Borrowed Data, Cow Type, and Safe Destructors
A technical guide on advanced Rust API design explores the trade-offs between storing owned data versus references, advising that ownership should be required only when the code genuinely needs it. The Cow (Clone-on-Write) type is highlighted as a solution for cases where ownership requirements are only known at runtime, allowing functions to borrow data when no modification is needed and clone it only when mutation is required. Small primitive types like i32 and bool are treated as exceptions, where copying is as cheap as referencing, while large types such as fixed-size arrays should still be passed by reference. The guide also addresses destructors via the Drop trait, noting they are typically expected to be non-blocking and infallible, though exceptions exist when releasing certain resources. Practical code examples illustrate how Cow can be used in function signatures to avoid unnecessary heap allocations.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in