Hacker News new | ask | show | jobs
by a1369209993 2728 days ago
> Borrowing

The way I think about this (which isn't quite how rust seems to) is that every value (including references) is always destroyed by passing it to a function, but gets implicitly copied if (arg is copyable && arg is referenced below). Eg:

  T a = mkT() # create value
  foo(&a) # create and immediately destroy/pass reference
  bar(a) # => bar(copy(&a)) # create-and-pass copy
  baz(a) # last use, so dont bother copying
For noncopyable values, this makes perfect sense; the callee got a value, so that value must have been moved out of the caller's variable. Treating copyable values the same way modulo the existence of a (T const ref -> T) copy function is just good consistency/orthogonality.
1 comments

is always destroyed by passing it to a function, but gets implicitly copied if (arg is copyable && arg is referenced below)

I am not sure what you are trying to say. This:

  bar(a) # => bar(copy(&a)) # create-and-pass copy
  baz(a) # last use, so dont bother copying
is not possible in Rust if a's type is not a copy type. a will be moved when calling bar, so trying to pass it to baz will result in a compiler error.

The story is quite simple: a value is always moved in a function call, unless it is a copy type (the type implements the Copy trait). When the type is a copy type, a bit-wise copy is made. References are not special: immutable references are copy types. Mutable references are not copy types (otherwise, they could be aliased).

You can find an overview of all copy types in the standard library in the implementations section of the Copy trait:

https://doc.rust-lang.org/beta/std/marker/trait.Copy.html#fo...

> I am not sure what you are trying to say. [Couple paragraphs rephrasing what I said]

Yep, that's what I was trying to say. (Although I'd hadn't remembered that the Copy trait actually enforced bitwise-exact-copies-only, because why would you want (implicit) non-exact copies.)