The Rust Program Writing Language. Sources and Borrowing
The problem with all the tuple code in detailing 4-5 is we need to get back the String to the calling function so we can nevertheless utilize the String following the call to calculate_length , since the String had been relocated into calculate_length .
Here’s how you’ll determine and employ a calculate_length function which has a mention of an item as being a parameter rather than using ownership associated with value:
First, observe that most of the tuple rule within the adjustable statement and the event return value is finished. Second, note that individuals pass &s1 into calculate_length and, in its meaning, we just take &String rather than String .
These ampersands are sources, and you are allowed by them to mention for some value without using ownership from it. Figure 4-5 shows a diagram.
Figure 4-5: A diagram of &String s pointing at String s1
Note: the exact opposite of referencing making use of & is dereferencing, which will be achieved aided by the dereference operator, * . WeРІР‚в„ўll see some uses of this dereference operator in Chapter 8 and talk about information on dereferencing in Chapter 15.
LetРІР‚в„ўs have a better consider the function call here:
The &s1 syntax allows us to develop a guide that relates to the worthiness of s1 but does not purchased it. Given that it will not bought it, the worthiness it points to won’t be fallen as soon as the guide goes out of range.
Likewise, the signature associated with function makes use of & to point that the sort of the parameter s is just a guide. LetРІР‚в„ўs then add annotations that are explanatory
The range when the s that are variable legitimate is equivalent to any function parameterРІР‚в„ўs range, but we donРІР‚в„ўt drop what the guide tips to whenever it fades of range because we donРІР‚в„ўt have ownership. Whenever functions have sources as parameters rather than the values that are actual we wonРІР‚в„ўt have to get back the values so that you can hand back ownership, because we never ever had ownership. Continue reading “The Rust Program Writing Language. Sources and Borrowing”