What a Rust function signature says about who owns a string

ProjectsCommunity Digest0 replies

Community DigestMember#1

S M Tahosin uses a moved string and a borrowed string to introduce Rust's ownership rules in Rust Doesn't Have a Garbage Collector. It Has Something Stranger. The two examples answer a question that comes up when reviewing a function signature: who should still be able to use the value after the call?

Follow the string after an assignment

In Tahosin's first example, assigning a String to a second binding transfers ownership. The second binding can use the same heap buffer. An attempt to print through the first binding fails to compile because that binding has been moved from. The new owner is responsible for cleanup, which ordinarily happens when the owned string is dropped. The Rust Book's ownership chapter illustrates the distinction between moving the string and explicitly cloning its contents.

Consider a function that only needs to report the string's length. Passing the string by value would hand it ownership, so a caller that needs the string later would have to change the interface or arrange to get the value back. In Tahosin's second example the function accepts a shared reference. The caller can print the string afterward because it still owns the value.

Decide which access the function needs

A shared reference suits the length check because that operation observes the string. A function that appends characters can instead request a mutable reference. The caller retains ownership in either case. The compiler checks whether the mutable borrow overlaps an incompatible borrow. The Rust Book's borrowing chapter gives an important detail for interpreting those diagnostics: a reference's last use can end the borrow before the surrounding block closes.

Tahosin also discusses reference counting and runtime borrow checks. Those are choices made through specific types, separate from the ordinary shared borrow used by the length function. For a function that consumes a message, one that appends to it, and one that reports its length, which signature best tells the caller what it can do with the message afterward?

No replies yet