Rust newbie question. My understanding is that alm...
# development
h
Rust newbie question. My understanding is that almost always, you want to use
&str
instead of
String
for a function's argument as it's more flexible. Same with using slices in args In a couple of our workunit functions, like
with_workunit
, we use
String
. Do you know if that's for a particular reason?
Same with using slices in args
Iiuc,
&str
is a type of slice
e
If you see an & there is a lifetime involved. If you have a future you need the static lifetime which you can't get for a dynamic string value ... so you tend to need ownership. String gives you that.
đź‘Ť 1
w
there can be good reasons to take an owned value as well
in the workunit case, the ownership of the given String moves into the workunit… ie, it lives on beyond the end of the function
đź‘Ť 1
if that function boundary were to take a
&str
, the caller might create a
String
and throw it away, and the callee would need to copy it
there are ways to “maybe clone” things (the
Cow
type), but you only need them if the callee is not “definitely” going to take ownership
đź‘Ť 1
and one more bit of spiel: the (
&str
,
String
), “borrowed”/“owned” dichotomy extends to a bunch of other types… including (
&[T]
,
Vec<T>
) , (
Path
,
PathBuf
), etc
đź‘Ť 1
e
This is the poster child for the ownership section in the book. Presumably you're reading that, but in case you missed it: https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html