#Values And References
Status: language specification draft.
This chapter defines reference types and reference expressions: their syntax, their typing, and what they do at run time. A reference type is a counted reference type, *T or *mut T, or a local reference type, &T or &mut T. Its values refer to a T that lives elsewhere.
*T and &T read the T they refer to, and *mut T and &mut T also write it. A counted reference may be stored, returned, and captured. A local reference is lent to a call and never kept past it.
&e and &mut e make local references. A counted reference refers to an object that box makes, which holds a copy of a value.
struct Body:
pos: Point
vel: Point
fn drift(body: &mut Body, step: &Point) -> void:
body.pos = *step
fn spawn(pos: Point) -> *mut Body:
box(Body { pos: pos, vel: Point { x: 0, y: 0 } })#Reference Types
A reference type is *, *mut, &, or &mut followed by a type.
fn first(items: List[*Point]) -> Option[*mut Point]:
.None
fn each(f: fn(&Point) -> *mut Point, pending: *Point?) -> void: pass- ref.type.forms
&Tis a local reference type, and&mut Tis a writable local reference type. The operandTis a named,dyn, tuple, or grouped type, or a counted reference type with no parentheses:&*T,&*mut T, and&mut *T. - ref.type.counted-forms
*Tis a counted reference type, and*mut Tis a writable counted reference type. Their operand is a named,dyn, tuple, or grouped type. - ref.type.kindsCounted and local are the two kinds of reference. A rule of this chapter that says "a reference" holds for both kinds.
- ref.type.kinds.elsewhereA rule in another chapter that writes
&Tor&mut Tfor a reference that is read, written, matched, compared, or printed holds for*Tand*mut Ttoo. It does not extend which implementations a reference type has:ref.type.kind-implalone decides that. This rule is temporary, as the note below says. - ref.type.local-uncountedA local reference counts nothing at run time: making, copying, or ending one changes no count. Only a counted reference holds a count of the object it refers to.
- ref.type.positionA counted reference type may appear wherever a type may: a parameter, a result, a field, a binding annotation, a type argument, and a function type's parameters and result.
- ref.type.optional
?applies to the whole reference type:*T?is an optional*T. - ref.type.groupTo refer to an optional, to a local reference, or from a counted reference to another reference, group the operand:
&(T?),&(&T), and*(*T).&(*T)is the same type as&*T. - ref.type.no-nesting
&&Tis a syntax error, because&&is one token. So are&mut mut T,mut &T, and*&T. Error:syntax-error. - ref.type.counted-no-nesting
**Tis a syntax error too, because**is one token, so a counted reference to one is written*(*T). So are*mut mut Tandmut *T. Error:syntax-error. - ref.type.no-function
&never directly precedesfn:&fn() -> i32and&mut fn() -> i32are errors. Error:syntax-error. - ref.type.counted-no-function
*never directly precedesfneither:*fn() -> i32and*mut fn() -> i32are errors. Error:syntax-error. - ref.type.distinct
&Tand&mut Tare distinct types. Each is invariant inT:&Ais&Bonly whenAisB. - ref.type.kind-distinct
*Tand*mut Tare distinct types, and distinct from&Tand&mut T. Each is invariant inT. - ref.type.kind-implAn implementation for a reference type covers that kind only. One for
*Tdoes not cover&T, and one for&Tdoes not cover*T; so too for*mut Tand&mut T. Using a&Twhere only*Timplements a bound is an error. Error:unsatisfied-trait-bound. - ref.type.any-refA reference type implements
AnyRef. - ref.type.dyn
&dyn Trand&mut dyn Trare trait value references, whose conversions and members Trait Value References states. - ref.type.dyn-counted
*dyn Trand*mut dyn Trare counted trait value references. They take the same conversions and members, with*in place of&on both sides of each conversion. - ref.type.dyn.no-fn
Fnhas no trait-value reference form, so local and counteddyn Fnreferences are errors. Error:invalid-dyn-type. - ref.type.dyn.no-fn-mut
FnMuthas no trait-value reference form either. Error:invalid-dyn-type.
Note.
ref.type.kinds.elsewherebridges the chapters until the respelling slices of #834 spell each such rule for both kinds. Those slices then remove it.
Why. A counted
*Tholds a count and a local&Tholds none, so one compiled body cannot serve both kinds. As in Rust, an implementation for one reference type covers that type alone, and code that needs both kinds writes both implementations.
use std.function.{Fn, FnMut}
trait Named:
fn name(&self) -> string
impl Named for *Point:
fn name(&self) -> string: "point"
fn label[T < Named](value: T) -> string: value.name()
fn bad_kind(p: &Point) -> string: label(p) # error: unsatisfied-trait-bound
fn bad_and(p: &&Point) -> void: pass # error: syntax-error
fn bad_mut(p: mut &Point) -> void: pass # error: syntax-error
fn bad_fn(f: &fn() -> i32) -> void: pass # error: syntax-error
fn bad_power(p: **Point) -> void: pass # error: syntax-error
fn bad_dyn(f: &dyn Fn(i32) -> i32) -> void: pass # error: invalid-dyn-type
fn bad_dyn_mut(f: &mut dyn FnMut(i32) -> i32) -> void: pass # error: invalid-dyn-typeSee also: Modifiers, Optionality, And Grouping.
#Reference Expressions
A reference expression is a prefix operator and its operand. &e and &mut e make a reference, and *e reads through one.
fn demo(r: &mut Point, items: List[Point], i: i32) -> void:
inspect(&items[i])
edit := &mut r.x
copy := *r
*r = Point { x: 1, y: 2 }
made := &Point { x: 3, y: 4 }- ref.expr.make
&eand&mut eare prefix expressions. Their operand is aunary_expression. - ref.expr.literalA data expression is an ordinary operand, so
&Point { x: 1, y: 2 }and&mut Box::[i32] { value: 1 }are reference expressions around a literal. - ref.expr.deref-operand
*eis a prefix expression. Its operand is a postfix expression, another*e, or a prefix expression such as&xor-x. - ref.expr.deref.target
*emay be the left side of=and of a compound assignment, as in*r = vand*r += 1. - ref.expr.star-binary
*is a prefix operator only. Between two operands it stays multiplication, and*=stays compound assignment.
#Precedence
The prefix & and &mut bind like the prefix ! and the unary -. The prefix * binds like a postfix suffix, tighter than **.
- ref.prec.binary-tighter
&and&mutareunary_expressionoperators. They bind more tightly than every binary operator except**, and less tightly than every postfix suffix. - ref.prec.deref
*binds more tightly than every binary operator,**included, and less tightly than every postfix suffix. - ref.prec.postfixThe operand includes the postfix suffixes after it.
&a.b[i]is&(a.b[i]), and*r.xis*(r.x). - ref.prec.groupTo dereference before a suffix, group the operand:
(*r).x. - ref.prec.power-refThe operand of
&and&mutincludes**, as for unary-.&x ** 2is&(x ** 2). - ref.prec.power-derefThe operand of
**may be a dereference.*r ** 2is(*r) ** 2, and2 ** *ris2 ** (*r). - ref.prec.nestedPrefix operators nest from the right.
&*ris&(*r),*&xis*(&x), and-*ris-(*r). - ref.prec.operand-positionA
&or*that begins an operand is a prefix operator. After an operand it is the binary bitwise and or multiplication, soa & &bisa & (&b).
fn precedence(r: &mut Point, items: List[Point], i: i32, a: i32, b: i32) -> void:
inspect(&items[i].x) # inspect(&(items[i].x))
two := *r.x # *(r.x)
three := (*r).x # a field of the value
four := a & &b # bitwise and of a with a reference
five := a * *b # multiplication of a by a dereference
six := *r ** 2 # (*r) ** 2
seven := &r ** 2 # &(r ** 2)Why. A reader who knows
-a.band!a.balready knows&a.b. A dereference reads a value, so*r ** 2squares the value*r, asr.x ** 2squares a field.
#Operator Tokens
- ref.token.and-and
&&is the logical and operator and nothing else.&&xis a syntax error, so a reference to a reference is written& &xor&(&x). Error:syntax-error. - ref.token.caret
^is only the exclusive-or operator. It has no prefix form and no meaning in a type. Error:syntax-error. - ref.token.and-boundIn a generic bound list,
&still joins bounds, as inT < Display & Debug.
fn tokens(a: bool, b: bool, x: i32, y: i32) -> void:
both := a && b
bits := x & y
flip := x ^ yfn bad_expr(x: i32) -> void:
r := &&x # error: syntax-error
s := ^x # error: syntax-errorSee also: Unary And Binary Operators.
#Places And New Objects
&e and &mut e make a local reference: to e when e is a place, and to a new object holding a copy of e otherwise.
struct Point:
x: i32
y: i32
fn make() -> Point:
Point { x: 1, y: 2 }
fn demo() -> i32:
let mut p = Point { x: 0, y: 0 }
r := &mut p # refers to p, as a local &mut Point
r.x = 5 # p.x is now 5
q := &mut p.y # refers to the field y of p
*q = 7 # p.y is now 7
n := &make() # a new object holding the result
m := &mut Point { x: 3, y: 4 } # a new object
p.x + n.y + m.x- ref.place.formsLocals and parameters of any binding form, and top-level bindings, are places for
&and&mut. A struct field of a place and a value reached through a reference are places too. - ref.place.through
*rwith a referenceris a place, and so is a field read throughr, such asr.x. The referenceris evaluated once, when the reference to the place is taken. - ref.place.elementA list element and a map value are places too. A reference to one is an element reference, which lives for one call.
- ref.expr.place
&eand&mut eon a place refer to that place. A later write to the place, through any path, is seen through the reference. - ref.expr.allocate
&eand&mut eon any other expression evaluateeand refer to a new object that holds the value. Each evaluation makes a new object. - ref.expr.allocate.writableA new object is writable, so
&mut T { ... }and&mut make()are valid. - ref.expr.kind.always-local
&eis always a local reference&T, and&mut ea&mut T, whereTis the type ofe. The expected type never makes it counted. - ref.expr.kind.no-counted
&eor&mut ewhere a counted reference type is expected is an error, asref.local.escape.countedstates. Error:local-reference-escapes. - ref.expr.kind.no-counted.adviceThe diagnostic tells the writer to box the value at its declaration, as
p := box(Point { x: 0 }). It offers no fix-it, since boxing at the use would copy the value. - ref.place.aliasTwo references to one place, or two copies of one reference, see each other's writes.
- ref.place.receiver.localA call of a
&selfor&mut selfmethod on a place takes a local reference to it, as&and&mutwould. - ref.place.receiver.countedA call of a
*selfor*mut selfmethod on a place is an error, asfn.method.counted-self.placestates. Reference Receivers states the rules of both calls. - ref.place.tuple-elementA tuple element of a place is a place for
&and&mut, as a struct field is:&mut pair._1refers to the element insidepair. The rules this chapter states for a field reference apply to it.
struct Point:
x: i32
fn keep(p: *mut Point) -> void: pass
fn invalid() -> *Point:
let mut p = Point { x: 0 }
keep(&mut p) # error: local-reference-escapes
&p # error: local-reference-escapesWhy. A reference to a value that is not a place still needs storage to refer to, so it gets a new object, as Go's
&T{...}does. Sharing beyond one call starts withbox, so&never decides between a local and a counted reference.
#Boxes
box(e) makes a new object that holds a copy of the value of e, and returns a counted reference to it.
struct Point:
x: i32
y: i32
struct Holder:
point: *mut Point
fn demo() -> i32:
shared := box(Point { x: 0, y: 0 }) # a new object, as a *mut Point
holder := Holder { point: shared } # the holder shares the object
shared.x = 5 # holder.point.x is now 5
let view: *Point = shared # the same object, read-only
let mut p = Point { x: 1, y: 1 }
copy := box(p) # a new object holding a copy of p
p.x = 9 # copy.x is still 1
holder.point.x + view.x + copy.x # 11- ref.box.declaration
std.coredeclaresboxas@intrinsic pub fn box[T](value: T) -> *mut T, and the prelude supplies it. The declaration is ordinary hd, and the compiler supplies only its body. - ref.box.checkA
boxcall is checked by the plain call rules, soTis inferred from the argument and the expected type as for any generic call. - ref.box.new
box(e)evaluateseonce and returns a*mut Tto a new object that holds the value. Each call makes a new object. - ref.box.copyThe new object holds a copy of the value. When
eis a place, a later write to that place is not seen through the result, and a write through the result does not change the place. - ref.box.weakenThe result converts by the rules of Conversions and Trait Value References, so it may be used where
*Tor*mut dyn Tris expected. - ref.box.localWhen the type of
eholds a local reference, so does the type ofbox(e), byref.local.holding.counted. The result is then local: it follows every rule of Local References, as aList[&T]does. - ref.box.objectEvery counted reference refers to a whole object: one that
boxmade, or one that another rule names as a new object. No expression makes a counted reference to a local, a parameter, a top-level binding, a field, or an element. - ref.box.lifetimeA counted reference keeps the object it refers to alive. It may outlive the block that made it, and may be returned.
- ref.box.rootThe local or parameter that holds the first counted reference a live local reference's place passes through, its root, stays alive until the reference's last use: its release, or a move of its value, waits for that use, in a suspending function's frame too.
- ref.count.pointerA local reference whose place passes through a counted reference keeps nothing alive. Its root keeps the object alive (
ref.box.root), and a replacement through another alias panics (ref.excl.alias.conflict). - ref.count.localA local reference is an address that keeps nothing alive. The local, parameter, field, element or object it points into outlives it (Local Scope).
- ref.count.new-objectThe new object that
&emakes (ref.expr.allocate) lives until the last use of the reference that made it and of every copy of that reference.
struct Point:
x: i32
struct Holder:
point: *(&Point) # error: local-reference-escapes
fn shadow() -> void:
box := Point { x: 1 } # error: prelude-name-shadowNote. No counted reference refers to a field, so no function hands out a writable reference into a field of its parameter:
&mut pair.leftis local and cannot be returned. A field that several holders share is declared*mut Tand holds a box, as a Swift class field holds a reference.&mut pair.leftstill lends the field for one call.
Why. Every counted reference starts at an object, so the runtime counts and frees whole objects and never follows a reference into the middle of one. A box copies, as Go's
newand OCaml'srefdo, so sharing starts where the value is boxed, not where it is used.
See also: Prelude Functions, Captured References.
#Writable Places Of References
&mut e on a place needs the place to be writable.
- ref.place.writable
&mut eon a place requires a writable place. Alet mutlocal, amutparameter,mut self, and a value reached through a writable reference,*mutor&mut, are writable. A struct field of a writable place is writable too. - ref.place.writable.top-levelA top-level binding is writable when it is bound with
let mut. - ref.place.writable.collection
&mutof a list or a map value in a writable place is valid. A change through the reference changes that place. - ref.place.writable.enum
&mutof an enum value in a writable place is valid: alet mutlocal, amutparameter, or a struct field of one.*r = vthrough&mut Ereplaces the whole value. A copied payload binding is no place (ref.match.copy), so&mutof one is an error by the rows below. - ref.place.shared-any
&eneeds no writable place: it may refer to a:=binding, a plainletbinding, or a value parameter.
&mut of a place that is not writable is an error, by what holds the place:
| Rule | The place is held by | Error |
|---|---|---|
| ref.place.not-writable.using-splitShort binding | a :=, using, or using! binding |
non-reassignable-binding |
| ref.place.not-writable.paramParameter | a value parameter or self that is not mut |
non-reassignable-parameter-binding |
ref.place.not-writable.letPlain let |
a let binding without mut |
not-writable |
| ref.place.not-writable.shared-referentRead-only reference | the value directly referred to by a read-only reference, *T or &T |
not-writable |
- ref.place.not-writable.fixFor a plain
letbinding and a value parameter, the diagnostic's fix-it writesmutbefore the binding's name.
fn invalid(count: i32) -> void:
let total = 0
r := &mut total # error: not-writable
fixed := 1
s := &mut fixed # error: non-reassignable-binding
t := &mut count # error: non-reassignable-parameter-bindingSee also: Writable Places.
#Conversions
A writable reference converts to a read-only one, and a counted reference lends itself as a local one.
- ref.convert.weakenA writable reference converts implicitly to the read-only one of its kind:
*mut Tto*T, and&mut Tto&T. A*mut Talso converts to*T?where an optional is expected. The conversion makes no new reference: both refer to the same place. - ref.convert.lendA counted reference converts implicitly to a local one where a local reference is expected:
*Tto&T, and*mut Tto&mut Tor&T. Both refer to the same place. - ref.convert.lend.loanConverting a
*mut Tto&mut Ttakes an exclusive run-time loan on the whole object it refers to, for the&mut's lifetime. Converting it to&Ttakes a shared loan. Each holds as a dereference in a reference's path does underref.excl.alias.call-loan, so a conflicting access through another*mutpanics. Panic:borrow-conflict. - ref.convert.no-upgradeA read-only reference,
*Tor&T, never converts to a writable one,*mut Tor&mut T. Using one where a writable reference is expected is an error. Error:mutable-upgrade. - ref.convert.no-countedA local reference never converts to a counted one, as
ref.local.escape.countedstates. - ref.convert.listed-onlyReference conversions are limited to this section and Trait Value References.
- ref.convert.readonly-covariantA readonly container reference permits
*mut Uto*Uweakening through covariant container arguments and tuple elements. - ref.convert.readonly-payloadThe same weakening enters an enum argument beneath a readonly reference when every field of the enum that mentions that type parameter is exactly the parameter, a whole payload or shared field, as
Tis inOption[T]; a parameter inside a field's type, as in*mut TorList[T], keeps its declared variance. - ref.convert.readonly-invariantThe conversion preserves invariant arguments and the operands of mutable references retained in the target.
- ref.convert.readonly-representationThe conversion preserves representation and reference identity, without copying elements or inserting wrappers.
fn edit(r: &mut i32) -> void:
*r += 1
fn view(r: &i32) -> i32:
*r
fn invalid(r: *i32) -> *mut i32:
edit(r) # error: mutable-upgrade
r # error: mutable-upgrade#Local References
A local reference, &T or &mut T, is lent to a call: a function may read and write through it, and pass it on, but never keep it.
struct Point:
x: i32
y: i32
struct Holder:
point: *mut Point
fn nudge(p: &mut Point) -> void:
p.x += 1
fn bump(p: &mut Point) -> void:
q := p # a local binding of a local reference
nudge(q) # passed on to a &mut parameter
fn demo(h: Holder) -> i32:
let mut origin = Point { x: 0, y: 0 }
nudge(&mut origin) # a local reference argument
let r: &mut Point = &mut origin # local: the annotation expects &mut
bump(r)
nudge(h.point) # a *mut Point lends itself as a &mut Point
origin.x- ref.local.usesA local reference may be the value of a parameter, a local binding, a call argument, or a receiver.
- ref.local.argumentPassing a local reference to a
&Tor&mut Tparameter is valid, so a function may pass on what it was lent. - ref.local.holdingA type holds a local reference when it is a local reference type, or a tuple, an optional, an instance of a generic type, or a type alias whose type or type argument holds one. An opaque type that borrows holds one too.
- ref.local.holding.countedA counted reference type,
*Tor*mut T, holds a local reference whenTholds one. - ref.local.self.keepA
&selfor&mut selfreceiver is a local reference, so these rules apply toselfin such a method. A method that keepsselftakes*selfor*mut self(Reference Receivers). A&selfmethod may still return a value that depends onself(Dependent Results). - ref.local.escape.countedA local reference never converts to a counted one. Using one where a counted reference is expected, as for a
*Tparameter or field, is an error. Error:local-reference-escapes.
A local reference escapes when it reaches one of these positions, and each is an error:
| Rule | A local reference | Example | Error |
|---|---|---|---|
| ref.local.escape.fieldField | is stored in a struct field or an enum payload field, or a field's declared type holds one | point: &Point |
local-reference-escapes |
| ref.local.escape.elementCollection element | is stored as an element of a list, a map, or a set whose element type holds no local reference, by a literal or a method such as push |
points.push(p) |
local-reference-escapes |
| ref.local.escape.top-levelTop-level binding | is bound by a top-level binding | let origin_ref: &Point = &origin |
local-reference-escapes |
| ref.local.escape.fn-value-resultFunction value result | is the result of a function value whose type gives it no source among the inputs, as for a method bound to its receiver | p::x_ref for fn x_ref(&self) -> &i32 |
local-reference-escapes |
| ref.local.escape.capture-storedStored closure capture | is captured by a closure outside a direct fn(...) argument, a type parameter field, and a type parameter argument, a captured self included |
fn() -> i32: p.x |
local-reference-escapes |
| ref.local.escape.trait-argumentTrait argument | is a type argument of a trait or a trait value, written or inferred | dyn Store[&Point] |
local-reference-escapes |
- ref.local.escape.position-messageThe diagnostic's message names the position the reference escapes to, a row of the table above or a counted reference.
- ref.local.capture-parameterA closure supplied directly for a
fn(...)parameter may capture a local reference underfn.capture.local-parameter. - ref.local.capture-originSuch a function value carries the captured reference's origin while it remains in the call's dependent scope.
struct Point:
x: i32
struct Holder:
point: &Point # error: local-reference-escapes
origin := Point { x: 0 }
let origin_ref: &Point = &origin # error: local-reference-escapes
fn keep(points: &mut List[*Point], p: &Point) -> void:
points.push(p) # error: local-reference-escapes
impl Point:
fn x_ref(&self) -> &i32:
&self.x
fn bound(p: Point) -> i32:
f := p::x_ref # error: local-reference-escapes
*f()
fn reader(p: &Point) -> fn() -> i32:
fn() -> i32: p.x # error: local-reference-escapesWhy. Most references are lent for one call, as Swift's
inoutparameters are. A counted reference is a separate ownership choice, not a mechanical repair for a local reference that escapes.
See also: Captured References, Reference Receivers.
#Dependent Results
A function's result may hold a local reference that it borrows from its receiver or a parameter, its source. Such a result is a dependent result.
struct User:
name: string
tags: List[string]
impl User:
fn name(&self) -> &string: # depends on self
&self.name
fn tags_mut(&mut self) -> &mut List[string]:
&mut self.tags
fn named(&mut self, name: string) -> &mut User:
self.name = name
self
fn tagged(u: &User) -> &List[string]?: # one reference position: depends on u
if u.tags.len() > 0: .Some(&u.tags) else: .None
fn demo(u: &mut User) -> void:
n := u.name() # n borrows all of u while it is used
t := u.tags_mut()
t.push("x") # writes u.tags in place- ref.dep.resultA function's or a method's result type may hold a local reference:
&T,&mut T, a tuple of them, or an instance of a generic struct or enum, such as&T?orResult[&T, E]. - ref.dep.result.opaqueAn opaque result type that borrows is a dependent result too, and its hidden value follows these rules (Opaque Results That Borrow).
- ref.dep.positionEach
&or&mutin a parameter's type is one reference position: in&self, inp: &T, inopt: &T?, and in each element ofpair: (&A, &B). A&inside a function type is none. - ref.dep.capture-positionA direct
fn(...)parameter is one capture position with a fresh lifetime, and a direct function result has one capture position too. - ref.dep.capture-elideAn elided direct function result depends on the one direct function parameter's capture position.
- ref.dep.capture-elide.ambiguousA direct function result with two or more direct function parameters is an error, since it has no one capture position to depend on. Error:
ambiguous-reference-source. - ref.dep.elideIn a signature that writes no lifetime, a dependent result's source is
selfwhen the receiver is&selfor&mut self. Otherwise it is the parameter of the one reference position. - ref.dep.elide.noneIn a signature that writes no lifetime, a dependent result with no reference receiver and no reference position is an error. Error:
reference-result-without-source. - ref.dep.elide.ambiguousIn a signature that writes no lifetime, a dependent result with no reference receiver and two or more reference positions is an error. Error:
ambiguous-reference-source. - ref.dep.returnEvery value a function returns, by
returnor as its body's value, may depend only on its source. Error:local-reference-escapes. - ref.dep.return.messageThe diagnostic's message names the root the value depends on, as a local, a parameter's own storage, or another parameter. It has no fix-it.
- ref.dep.callA call's dependent result depends on what its source argument depends on.
- ref.dep.call.localThe result is a local reference value of the caller, so every rule of Local References applies to it. The caller may return it only as
ref.dep.returnallows. - ref.dep.call.pointerA dependent result whose source argument is a
*Tor*mut Tis a local reference to that argument's root, the local or parameter the pointer was read from, as&*pis. So afterr := boxed.slot()orr := borrow(boxed), a write throughboxedwhileris in use is an error (ref.excl.call), and so is a use ofroutside the scope of the localboxed(ref.dep.scope). Error:conflicting-accessfor the write,local-reference-outlives-localfor the use. - ref.dep.traitAn impl's method has the source of the trait method it implements. A call through a bound, an impl, or a trait value reference takes its source from the trait's signature.
- ref.dep.storeA value that holds a local reference, stored through a reference, must land in a place of the function. A store into a place the caller owns, as through
out: &mut (&T), is an error, unless the place's type names the value's lifetime (ref.lifetime.store). Error:local-reference-escapes. - ref.dep.callerWhile a dependent result is in use, the caller may read its source. It may write the source only as Writes While Borrowed allows. A read through the result sees the source's current value.
- ref.dep.temporaryA dependent result of a call on a temporary, as in
make().name(), keeps the temporary alive while the result is in use. - ref.dep.suspensionA suspension, the
Suspend[R]of a bang call made without!, holds every reference that its call's arguments hold, the receiver's included. It holds them in one position of its own, after the positions ofR. - ref.dep.suspension.localA suspension that holds a local reference is a local reference value of the caller, so every rule of Local References and
ref.dep.returnapplies to it. Error:local-reference-escapes. - ref.dep.suspension.outputEach position of
Rdepends on what the call's result would depend on with!, byref.dep.call. - ref.dep.suspension.countedA suspension retains a counted reference that its call lends, by itself or as the trait value behind it, by
ref.box.lifetime. So it holds no origin for that argument. - ref.dep.suspension.resultA
Suspend[R]in a declared result type has that position too. It depends on the one lifetime of the parameters' positions, or on every parameter under two or more. With no parameter position, it depends on nothing. - ref.dep.suspension.lifetime
Suspendtakes one optional lifetime argument after its result type, as inSuspend[R, 'a]. It names the suspension's own position, as a lifetime struct's argument names one of the struct's positions (ref.lifetime.struct.position). More than one is an error. Error:argument-count. - ref.dep.suspension.lifetime.fieldA field typed
Suspend[R, 'a]in a lifetime struct may hold a suspension that holds'adata. A field that writes no lifetime for its suspension holds one that holds no local reference. - ref.dep.suspension.storeA suspension that holds a local reference never reaches a box, a provider, a host call, a top-level binding, or a struct field that is neither of a type parameter nor written with a lifetime. A list, a map, a tuple, or an optional keeps it in its own positions. Error:
local-reference-escapes.
fn count!(s: &string) -> usize:
s.len()
fn later(s: &string) -> Suspend[usize]: # holds what s refers to
count(s)
fn now!() -> usize:
local := "x"
count!(&local)
struct Pending['a]:
task: Suspend[usize, 'a]
fn soon(s: &string) -> Pending: # holds what s refers to
Pending { task: count(s) }struct User:
name: string
fn bad_local() -> &string: # error: reference-result-without-source
u := User { name: "a" }
&u.name
fn bad_pick(a: &User, b: &User) -> &User: # error: ambiguous-reference-source
a
fn bad_compose(f: fn(i32) -> i32, g: fn(i32) -> i32) -> fn(i32) -> i32: # error: ambiguous-reference-source
fn(x: i32) -> i32: g(f(x))
fn bad_value(u: User, other: &User) -> &string:
&u.name # error: local-reference-escapes
fn bad_store(out: &mut (&User), u: &User) -> void:
*out = u # error: local-reference-escapes
fn hold!(r: &string) -> usize:
r.len()
fn bad_suspension() -> Suspend[usize]:
local := "x"
hold(&local) # error: local-reference-escapesWhy. These are Rust's elision rules for a result's lifetime, with no lifetime written. Lifetime Variables gives the rules for a signature that writes one. A write to the source replaces the value in its place, and the place stays where it is, so the caller needs no exclusive access. A suspension holds its arguments as a Rust
async fnfuture captures every input lifetime.
#Origins
An origin is a storage root that a local reference may point into. It is what a parameter refers to, which the caller owns, or a local of the function, the hidden local of &e on a value included. It may also be a parameter's own storage, which the call owns.
- ref.dep.origin.setEach value that holds a local reference has an origin set. The checker solves the sets once per function, per binding, regardless of the order of statements.
- ref.dep.origin.leastThe sets are the least solution of the constraints in the table below. A reassignment adds origins and never removes them.
- ref.dep.origin.positionA value has one origin set per reference position outside another reference, so the positions of
(&A, &B)and ofResult[&A, &B]have separate sets. - ref.dep.origin.position.partsA construction and a projection keep each part in its own positions: a tuple element, an optional's payload, and a field whose declared type is a type parameter. So does a lifetime struct's field of one lifetime (
ref.lifetime.struct.read). - ref.dep.origin.position.unionEvery position takes the union of all of them for any other part and for the hidden local of
&e. A reborrow of a part, shared or&mut, is not such a part:r := &t.xandr := &mut t.innerkeep that part's own positions. Nor is a store through a reference:*r = vandr.x = vput each position ofvinto its own position of the place.
| Rule | Expression | Origins |
|---|---|---|
| ref.dep.origin.paramParameter | p, for a parameter whose type holds a local reference |
what p refers to |
| ref.dep.origin.placePlace | &x or &x.f.g, or the automatic address a method call takes of such a place, for a local or a parameter x |
x's own storage |
| ref.dep.origin.elementElement place | &xs[i], &m[k], or an element reference loop binding |
the origin of the collection's root place |
| ref.dep.origin.reborrowReborrow | &r.f, &*r, or an automatic address through a reference value r |
the origins of r |
| ref.dep.origin.countedCounted crossing | a place reached through a counted reference, as &h.p.x with p: *mut P |
the origins of the place the counted reference was read from |
| ref.dep.origin.lendLent counted reference | a counted reference read from a place and lent as a source argument | that place's origins |
| ref.dep.origin.temporaryTemporary | &e on a value, and a &self call on a temporary |
a hidden local |
| ref.dep.origin.bindingBinding | a read of a binding b |
the union of every value stored into b anywhere in the function |
| ref.dep.origin.partsConstruction | a tuple, .Some(a), or a struct or enum literal |
the union of its parts, each in its positions |
| ref.dep.origin.projectionProjection | t._0, or a pattern binding of a scrutinee s |
the origins of the positions of t, or of s, that it reaches |
| ref.dep.origin.branchBranch | if or match as a value |
the union of its arms |
| ref.dep.origin.callCall | a call with a dependent result, whose source argument is a |
the origins of a |
| ref.dep.origin.tryWrap | x?, and an implicit .Some |
the origins of x |
struct User:
name: string
fn walk(u: &User) -> &string:
let mut r = &u.name # r gets what u refers to
spare := User { name: "x" }
if r.len() == 0:
r = &spare.name # r also gets spare
r # error: local-reference-escapes
fn optional(u: &User) -> &string?:
let o: &string? = .Some(&u.name)
match o:
.Some(n) => .Some(n) # valid: n has the origins of o
.None => .NoneWhy. Per-binding sets are the regions of Rust's non-lexical lifetimes without their flow sensitivity. A later stage may make them flow-sensitive and accept more programs.
#Local Scope
A local reference may point into a local of the function only while that local exists.
- ref.dep.scopeEvery use of a value whose origin set holds a local of the function, other than a parameter, must lie in that local's scope. Error:
local-reference-outlives-local. - ref.dep.scope.bindingA binding is in scope from the end of the statement that declares it to the end of the suite that holds that statement. A
matcharm's binding is in scope in its arm, and aforloop's binding in the loop's body. - ref.dep.scope.temporaryThe hidden local of
&eis in scope from the start of the statement that holds&eto the end of the suite that holds that statement. - ref.dep.scope.loopA local declared in a loop's body is out of scope in the loop's later iterations. Since origin sets ignore the order of statements, a read inside the loop of a binding declared outside it, whose origin set holds such a local, is a use in a later iteration.
- ref.dep.scope.messageThe diagnostic's message names the binding and the local, as in "
amay point intoc, whose block has ended". It has no fix-it.
fn pick(x: i32, b: bool) -> i32:
let a: &i32 = &x
if b:
c := +123
a = &c
*a # error: local-reference-outlives-local
fn last(x: i32) -> i32:
let a: &i32 = &x
for i in 0..3:
c := +4
a = &c
*a # error: local-reference-outlives-local
fn total(x: i32) -> i32:
let a: &i32 = &x
let sum = +0
for i in 0..3:
sum += *a # error: local-reference-outlives-local
c := +4
a = &c
sumStorage that must outlive its block is boxed at its declaration, and the binding holds a *T.
Why. This is Rust's E0597. Without it, such a local would need counted storage that no
boxmade, and&would not be truly local.
See also: Element References, Reference Receivers.
#Writes While Borrowed
While a shared reference to a place is in use, the place may be read but not changed or moved. While a &mut reference to it is in use, the place may not be used at all except through that reference.
struct User:
name: string
age: i32
impl User:
fn name(&self) -> &string:
&self.name
fn age_mut(&mut self) -> &mut i32:
&mut self.age
fn rename(u: &mut User) -> void $ Console:
n := &u.name
u.age += 1 # valid: another field
u.name = "b" # error: conflicting-access
println(*n) # the last use of n
u.name = "c" # valid
fn birthday(u: &mut User) -> void $ Console:
n := u.name() # n borrows all of u
println(u.age) # valid: a read
u.age += 1 # error: conflicting-access
println(*n) # the last use of n
u.age += 1 # valid
fn tag(u: &mut User) -> void $ Console:
a := u.age_mut() # a borrows all of u exclusively
println(u.age) # error: conflicting-access
*a += 1 # valid: through a, its last use
println(u.age) # valid
fn set_name(to: &mut string, from: &string) -> void:
*to = *from
fn copy_name(u: &mut User, v: &User) -> void:
set_name(&mut u.name, &u.name) # error: conflicting-access
set_name(&mut u.name, &v.name) # valid: another place- ref.excl.sharedWhile a shared reference
&pis live, a write topor to a place that overlaps it is an error. Error:conflicting-access. - ref.excl.mutWhile a
&mut pis live, a use ofpor of a place that overlaps it is an error, except through that reference. A use is a read, a write, a&p, another&mut p, or a closure that captures it. Error:conflicting-access. - ref.excl.placeExplicit references and implicit counted-to-local conversions follow these rules for local or parameter places, including fields and dereferences. Two places of one local overlap unless their paths name two different fields at the same depth.
- ref.excl.writeA write is an assignment to the place or a part of it, a
&mutof it that a binding keeps, or a call that takes&mutof it or a&mutbinding to it. A&mut selfmethod call is such a call. A built-in change writes too: a list'spushorreserve, a map store, and a map'sremove. A call's&mutwrites when the call runs, after its other arguments. - ref.excl.moveWhile a reference to
pis live, a move ofpor of a place that overlaps it is an error. A move is a read thatref.move.sites,ref.move.fieldorref.move.patternmakes a move. A copied value does not move, so reading it is valid. Error:conflicting-access. - ref.excl.liveThe reference is live until the last use of a binding whose origin set holds it, not until the end of the block. A use that the write or move cannot reach does not count: one in another arm of the same branch, or one after a
return. A use earlier in a loop counts when the binding is declared outside the loop. - ref.excl.reassignAssigning the binding a value whose origin set does not hold the reference ends the reference's use through it.
- ref.excl.declareA
letor:=makes a new local, so it writes no place a reference from an earlier iteration of its loop points into. - ref.excl.callThe
&a call takes for a&selfreceiver or a¶meter is a shared reference to the whole place it was taken from. A&mutbinding that a call takes as&lends the place it refers to in the same way. A&muta call takes, a passed-on&mutbinding included, lends the whole place as a&mutreference. A call's result that depends on that reference holds it (ref.dep.call), even where the result points into one field, unless its signature names that field (ref.result.path.caller). A result of type&mut Tholds that reference as a&mutone after the call, whatever the receiver or parameter kind, as when a&selfmethod returns a&mutthrough a*mutfield. - ref.excl.argsWhile a call takes a
&mutof a place, its other arguments and its receiver may not hold a reference to an overlapping place. An element reference falls underref.elem.conflictinstead. Error:conflicting-access. - ref.excl.args.afterAn argument after a written
&mut pargument may not usepor an overlapping place. The arguments of a&mut selfmethod call may read the receiver's place, as inxs.push(xs.len()). Error:conflicting-access. - ref.excl.args.sharedAn argument after a
&ofpthat the call takes, written or for a&selfreceiver, may not write or movepor an overlapping place:referred(&ys, ys.pop())is an error, andreferred(&ys, ys.len())is valid. An element reference falls underref.elem.conflictinstead. Error:conflicting-access. - ref.excl.args.pointerA
*Tor*mut Targument accesses its whole pointee for the call's other arguments: a*mutwrites it and a*Treads it. Soinspect(view, &mut view.n)andmutate(boxed, &boxed.n)are errors, andlook(view, &view.n)is valid. Passing a pointer is no access at run time. Error:conflicting-access.
struct Bag:
labels: List[string]
impl !Copy for Bag
fn consume(bag: Bag) -> usize:
bag.labels.len()
fn count(bag: Bag, names: List[string]) -> usize:
r := &bag
s := &names
copy := names # valid: a list is copied
k := r.labels.len() + s.len() + copy.len()
n := consume(bag) # valid: after the last use of r
n + k
fn early(bag: Bag) -> usize:
r := &bag
n := consume(bag) # error: conflicting-access
n + r.labels.len()Why. This is Rust's E0506, E0503, E0499 and E0505 with non-lexical lifetimes. A write while a shared reference is live would change what the reader sees behind its back, and a
&mutholder expects the same of its place. A move would leave the reference pointing at a value that another owner may free.A call's result locks its whole source, as in Rust, unless its signature names the field the result points into (Result Paths). The fixes are Rust's: make the change after the last use, copy the value out first (
name := *u.name()), or borrow only the field the code reads (&u.name).
#Conflicts Through Aliases
Another *mut to the same object is a path the compile-time rules do not see. Through it, a conflicting access to an object that a binding borrows panics at run time, as Rust's RefCell does.
struct Team:
lead: *mut User
fn rename(t: &Team, alias: *mut User) -> void $ Console:
n := &t.lead.name
alias.age += 1 # panics borrow-conflict when alias is t.lead: n holds all of it
println(*n) # the last use of n
alias.name = "c" # valid
m := t.lead.name() # a result of `fn name(&self) -> &string`
alias.age += 1 # panics borrow-conflict: m holds all of t.lead
println(*m)-
ref.excl.alias.loanA run-time loan is a
&por&mut pthat a:=orletbinding of type&Tor&mut Tholds, or that an optional, tuple or struct holds. It holds it directly, through a call's result that depends on it (ref.excl.call), or from another such holder by a copy or a move. The loan holds each object that a dereference of a*mutor a*Tinp's path reaches. A&mut pholds the last such object exclusively; every other object, and every object of a&p, is held shared. A*mutthat a call takes for a&selfor&mut selfreceiver lends the whole object it refers to. The loan is live until the last use of every binding that holds it and the release of every value that contains it (ref.excl.live). -
ref.excl.alias.counted-accessAn access through a counted reference is a use of a place whose path dereferences a
*mutor a*T. An assignment, a&mutand a built-in change of the place write the object its last dereference reaches; a read and a&read it. Every earlier object on the path is read. Passing a*mutor a*Tto a call is no access at run time; the callee's uses of it are. -
ref.excl.alias.conflictAn access through a counted reference panics when it writes an object a live run-time loan holds, or reads an object a live loan holds exclusively. A loan that the accessing function took through the same pointer, with the same root and path, does not conflict with it.
ref.excl.placealready checks that pair. Panic:borrow-conflict. -
ref.excl.alias.shared-counted-loanA reference held directly or through a call's result from a place reached through a
*Ttakes the same run-time loan as one reached through a*mut. -
ref.excl.alias.shared-variableA local variable that a closure shares is an object, as a
*mutpointee is. A reference whose place starts at the variable holds that object, and each use of the variable, in the closure or in its own function, is an access through a counted reference. -
ref.excl.alias.globalA top-level binding is an object. A reference whose place starts at the binding holds that object, and each use of the binding, from any function, is an access through a counted reference.
-
ref.excl.alias.call-loanA
&or&mutargument or auto-ref receiver whose path dereferences a*mutor a*Ttakes a run-time loan from its evaluation until its call returns. A&mut selfreceiver's loan is shared until the call begins, then exclusive. A closure argument holds the run-time loans of the references it captures until its call returns. -
ref.excl.alias.path-pointerA run-time loan holds each object its place's path reads a
*mutor a*Tfrom, so replacing such a pointer slot conflicts until the loan ends, in every build. -
ref.excl.alias.untracked-pathA reference whose place passes through no
*T, no variable a closure shares and no top-level binding a reference reaches takes no run-time loan, so an alias reads or writes its place in place.
See also: ref.convert.lend.loan, the loan a *mut T takes where it converts to &mut T or &T.
#Lifetime Variables
A lifetime variable 'a, written after &, names the lifetime of a local reference. The reference positions that write one variable share its lifetime:
struct User:
name: string
fn choose['a](a: &'a User, b: &'a User, first: bool) -> &'a User:
if first: a else: b # valid: a and b both have 'a
fn third['a](a: &'a User, b: &'a User, c: &User) -> &'a User:
c # error: local-reference-escapes
fn pick(x: &User, first: bool) -> usize:
let mut r = x
if first:
local := User { name: "local" }
r = choose(x, &local, first)
r.name.len() # error: local-reference-outlives-local
trait Named['a]:
fn name(&self) -> usize
fn borrowed_name(&'a self) -> &'a string
fn view(u: User) -> i32:
let r: &'a User = &u # error: references-not-yet-checked
0- ref.lifetime.formA local reference type may write a lifetime variable after
&:&'a Tand&'a mut T. - ref.lifetime.receiverA reference receiver may write one too:
&'a selfand&'a mut self. - ref.lifetime.countedA counted reference takes no lifetime variable, so
*'a Tis an error. Error:syntax-error. - ref.lifetime.declaredA lifetime variable names a lifetime parameter in scope, as Lifetime Parameters states.
- ref.lifetime.positionEach reference position of a signature has a lifetime: the variable it writes, or else a lifetime of its own.
- ref.lifetime.sharedPositions that write one variable share its lifetime, so a result position with that variable may depend on any of them.
- ref.lifetime.elideA result position that writes no lifetime takes a
&selfor&mut selfreceiver's lifetime, or else the parameters' one lifetime. - ref.lifetime.elide.noneSuch a position with no reference receiver and no parameter reference position is an error. Error:
reference-result-without-source. - ref.lifetime.elide.ambiguousSuch a position with no reference receiver, under two or more lifetimes of the parameters' positions, is an error. Error:
ambiguous-reference-source. - ref.lifetime.returnEach reference position of a returned value may depend only on the parameter positions of its lifetime, and on references reached through them. Error:
local-reference-escapes. - ref.lifetime.return.messageThe diagnostic's message names the root, the lifetime, and the parameters with that lifetime. It has no fix-it.
- ref.lifetime.callA call's result position depends on what every argument in a parameter position of its lifetime depends on.
- ref.lifetime.declarationsA top-level function, an implementation, and a method of an implementation or a trait may declare lifetime parameters.
- ref.lifetime.not-yet.local-or-newtype-ownerAny other lifetime parameter is not checked yet, so it is an error: a newtype's, a local function's, a local struct's, a local enum's, or a local alias's. A top-level struct's follows Lifetime Structs, a top-level enum's Lifetime Enums, a trait's Lifetime Traits, and a top-level alias's Lifetime Aliases. Error:
references-not-yet-checked. - ref.lifetime.alias-in-orderA type alias passes on the lifetimes written in its arguments when its type uses each parameter once, in order, outside function types, and writes no
&of its own. SoOption[&'a T]is&'a T?. - ref.lifetime.not-yet.aliasA lifetime written in the arguments of any other type alias is an error too. Error:
references-not-yet-checked. - ref.lifetime.not-yet.bodyA lifetime variable written inside a function body is an error too, but in a closure parameter's type, as
fn.type.lifetime.call.written.closurestates. There it is still an error inside a function type, a union, an opaque type or a projection. So is one in a trait value's binding, a context or rest type, or a type alias that holds a reference. Error:references-not-yet-checked.
struct User:
name: string
fn swap['a, 'b](x: &'a User, y: &'b User) -> (&'b User, &'a User):
(y, x) # (x, y) is an error: each position keeps its own origins
fn either['a](a: &'a User, b: &'a User, first: bool) -> &User: # the result takes 'a
if first: a else: bWhy. These are Rust's lifetime rules for functions: elision fills only the positions that write no lifetime, and a reference's referent outlives it. A lifetime is only checked; it adds nothing at run time.
See also: Lifetimes In Function Types, Method Generic Parameters, Lifetime Traits, Lifetime Aliases, Lifetime Implementation Targets, Lifetime Structs.
#Result Paths
A result reference may name the field of a reference parameter it points into, written after the & where a lifetime goes: &'self.name string. The result still has that parameter's lifetime. The body may return only a reference into that field.
struct Name:
first: string
last: string
struct User:
name: Name
age: i32
tags: List[string]
impl User:
fn first(&self) -> &'self.name string:
&self.name.first # valid: inside self.name
fn tags_mut(&mut self) -> &'self.tags mut List[string]:
&mut self.tags # valid
fn wrong(&self) -> &'self.name List[string]:
&self.tags # error: local-reference-escapes
fn whole(&self) -> &'self.name User:
self # error: local-reference-escapes
fn lead(a: &User, b: &User) -> &'b.name Name:
&b.name # valid: the result depends only on b
fn copy(u: User) -> &'u.name Name: # error: unknown-lifetime
&u.name
trait Named:
fn first(&self) -> &'self.name string # error: trait-method-signature
struct Team:
lead: User
size: i32
struct Crew:
lead: *mut User
size: i32
fn lead_name(c: &Crew) -> &'c.lead.name Name:
&c.lead.name # valid: the path crosses the `*mut`
fn birthday(u: &mut User, t: &mut Team) -> void $ Console:
n := u.first() # n borrows only u.name
u.age += 1 # valid: another field
u.tags.push("x") # valid
u.name.last = "b" # error: conflicting-access
println(*n)
tags := u.tags_mut() # tags borrows only u.tags, as `&mut`
println(u.age) # valid
tags.push("y")
m := t.lead.first() # m borrows only t.lead.name
t.size += 1 # valid
t.lead = *u # error: conflicting-access
println(*m)- ref.result.path.formA result path is a tick, a parameter's name, and one or more
.fieldsteps, written in the lifetime position of a local reference type:&'p.f Tand&'p.f mut T. Without a step,'pis a lifetime variable (ref.lifetime.declared). - ref.result.path.positionA result path is written only in a function's result type. Anywhere else it is an error. Error:
unknown-lifetime. - ref.result.path.paramThe name is a
&or&mutparameter's,selfincluded. Any other name is an error. Error:unknown-lifetime. - ref.result.path.fieldsEach step names a field of the struct the previous step reaches, starting from the parameter's referent. Any other step is an error. Error:
unknown-field. - ref.result.path.countedA step may cross a
*Tor*mut Tfield: the next step names a field of its referent, as'c.lead.namewithlead: *mut User. The path's place goes through the counted reference, as a written&c.lead.namedoes. The callee and caller rules treat the crossing as one more step of that place. - ref.result.path.not-yetA step through a local reference (
&Tor&mut T), and a result path on a reference inside another reference of the result, are not checked yet, so they are errors. Error:references-not-yet-checked. - ref.result.path.visibleEach field must be visible where the signature is written. Error:
private-member. - ref.result.path.publicA
pubsignature names only public fields, so private layout never enters an API. Error:private-type-leak. - ref.result.path.lifetimeThe result position has the parameter's lifetime, as if the signature wrote one variable on both.
- ref.result.path.calleeA returned value in that position must point into the path's place. It is a
&or&mutof a place that starts with the parameter and the path's fields, returned directly or through a binding. A value that may point elsewhere in the parameter's referent is an error. A call's result counts as pointing anywhere in its source. Error:local-reference-escapes. - ref.result.path.traitA trait's method names the whole
self, so its signature writes no result path. An implementation's method of a trait writes none either, since a bound or&dyncaller sees only the trait. Error:trait-method-signature. - ref.result.path.callerA call's result in a result path's position holds only that part of the place its argument was taken from: the place followed by the path's fields (
ref.excl.call). Foru.first()the result holdsu.name, and fort.lead.first()it holdst.lead.name. A&mutresult holds its part as&mut. - ref.result.path.caller.wholeThe result holds the whole place, as without a path, when the parameter's lifetime is also on a result reference that names no path of it, or on another parameter. When several result references name paths of one parameter, the result holds the fields those paths share.
- ref.result.path.tuple-elementA step may name an element of the tuple the previous step reaches, as in
-> &'t._1 stringwitht: &(i32, string).
Why. A signature that says which field a result points into lets a caller lock only that field, as a written
&u.namedoes. Private fields stay out of public signatures, so a layout change never breaks a caller. Only the body is checked against the path; a caller never depends on a callee's body.
#Lifetime Traits
A lifetime trait declares lifetimes which its methods may write:
struct Parser[T, 'src]:
src: &'src T
trait Source[T, 'src]:
fn source(&self) -> &'src T
impl[T, 'src] Source[T, 'src] for Parser[T, 'src]:
fn source(&self) -> &'src T:
self.src- ref.lifetime.traitEach lifetime argument of a trait instantiates that lifetime in its methods for implementations, bounds, and trait values.
- ref.lifetime.trait.impl-targetA trait implementation's target may write lifetimes which the implementation passes as the trait's lifetime arguments.
- ref.lifetime.trait.positionA trait value holds one reference position for each lifetime argument, after the positions of its type arguments.
- ref.lifetime.trait.bound-argumentA bound's trait arguments may write
&'a Tor&'a mut Twith a lifetime in scope, as inS < Store[&'a Point]. Such an argument is no escape to a trait argument. A call through the bound passes that argument at'a, so withs: &mut S,s.put(v)storesvinto a place the caller owns at'a(ref.lifetime.store.call), andvmust depend only on what a result of'amay depend on. The call checks each argument it passes at a bound's lifetime where it is made, whatever its result holds: withS < Mk['a, U]andfn make(&self, v: &'b Point) -> UinMk['b, U],s.make(&q)of a localqis an error, and so iss.pick(p, x)withxof a lifetime that need not outlive'a. A result of typeTis at'atoo (ref.lifetime.return). A call that instantiates such a parameter relates each slot of its type argument to'a, and where the argument is a type parameter whose bound writes a lifetime for the same slot, that lifetime to'a. An associated type's bound writes its trait's lifetimes, which the bound of the projection's base gives. Withtrait Shelf['b]: type Item < Store[&'b Point]andS < Shelf['a], a call throughS::Item's bound passes at'a. Each slot of an argument of typeS::Itemis at'aas well. A projection is also at each lifetime its trait's arguments name, asS::Itemoftrait Plain['b]: type ItemwithS < Plain['a]is at'a, and a value of a projection type returns as that type. A result of a projection type writes no reference, so no lifetime elides to it (ref.dep.elide). Withfn make(&self, v: &'b Point) -> Self::IteminShelf['b], the result is at'b, whichvis passed at, and not at the receiver's lifetime. A bound's lifetime arguments are passed the same way: withS < Store['a]andfn put(&mut self, v: &'b Point)inStore['b],s.put(v)storesvat'a. A trait's own bodies seeSelfbounded by the trait over its own parameters, so inShelf['b]'s default methodsSelf::Itemis at'bandself.put(v)stores at'b. Error:local-reference-escapes. - ref.lifetime.trait.bound-unnamedA
&Tor&mut Tthat writes no lifetime in a bound's trait arguments escapes to a trait argument, asref.local.escape.trait-argumentstates. A type parameter's bound, a supertrait, and an associated type's bound are each a bound. Error:local-reference-escapes. - ref.lifetime.trait.impl-argumentA trait implementation's trait arguments may write
&'a Tor&'a mut Twith a lifetime the implementation declares, as inimpl['a] Store[&'a Point] for Tally. Such an argument is no escape to a trait argument. The trait's methods take that argument at'a, as they take the target's lifetimes: withimpl['b] Id[&'b Point] for Sh,fn get(&self, v: V) -> Vis implemented by agetthat returns itsv: &'b Point. A call through the implementation passes each slot of one such lifetime as one, so withimpl['b] Put[&'b Point] for Cell['b],c.put(v)storesvintoc's'bplace (ref.lifetime.store.call). Error:local-reference-escapes. - ref.lifetime.trait.impl-unnamedA
&Tor&mut Tthat writes no lifetime there has a fresh lifetime parameter of the implementation, soimpl Store[&Point] for Tallymeansimpl['a] Store[&'a Point] for Tally. It is no escape to a trait argument either.
Why. This is Rust's rule. A bound states what a caller passes, so an unnamed reference there would say nothing about how long it lives. An implementation's header holds for every lifetime, so an unnamed reference there is general.
See also: Generic Traits, Lifetime Parameters.
#Lifetime Aliases
A top-level type alias may name and pass its declared lifetimes:
type Borrowed[T, 'src] = &'src T
type OptionalBorrowed[T, 'src] = Option[Borrowed[T, 'src]]- ref.lifetime.aliasEach lifetime argument of a type alias instantiates that lifetime wherever the alias's body writes or passes it.
See also: Lifetime Parameters, Transparent Aliases.
#Lifetime Implementation Targets
An implementation target may write a declared lifetime inside any reference position:
struct Wrap[T]:
value: T
trait Identity:
fn identity(self) -> Self
impl['a] Identity for Wrap[&'a string]:
fn identity(self) -> Self:
self- ref.lifetime.impl-targetAn implementation target may write any lifetime declared by the implementation, including in a type argument, and every method's
selfandSelfhave those lifetimes. - ref.lifetime.impl-target.assocA trait implementation's trait arguments and associated types may name a lifetime its target writes. A method whose trait result is built from such a trait argument or associated type, as
Item?inimpl['a] Iterator[&'a T] for RefIter[T, 'a]orSelf::Out, may return a reference of that lifetime. A call's result in that position depends onself's positions of it.
See also: Lifetime Parameters, Lifetime Traits, Lifetime Structs.
#Lifetime Structs
A lifetime struct declares lifetime parameters, and its fields may hold local references of those lifetimes:
struct Parser[T, 'src]:
src: &'src T
pos: usize
struct Holder:
parser: Parser[string] # error: local-reference-escapes
fn source['a](p: &Parser[string, 'a]) -> &'a string:
p.src
struct Two['a, 'b]:
x: &'a string
y: &'b string
fn left['a, 'b](t: &Two['a, 'b]) -> &'a string:
t.y # error: local-reference-escapes
fn src(p: &Parser[string]) -> &string: # error: ambiguous-reference-source
p.src
impl[T] Parser[T]: # error: references-not-yet-checked
fn position(&self) -> usize: self.pos
fn scan(fallback: &string) -> usize:
let mut p = Parser { src: fallback, pos: 0 }
if fallback.len() > 0:
text := "hello"
p = Parser { src: &text, pos: 0 }
p.pos # error: local-reference-outlives-local- ref.lifetime.structA top-level struct may declare lifetime parameters, as in
struct Parser[T, 'src]. - ref.lifetime.struct.fieldA field of a lifetime struct may write
&'a Tor&'a mut Twith one of the struct's lifetimes. Such a field is no escape to a field. - ref.lifetime.struct.argumentA type names a lifetime struct with one lifetime argument per lifetime parameter, as in
Parser[string, 'a]. The lifetime arguments take the lifetime parameters in order. - ref.lifetime.struct.argument.countA struct type with lifetime arguments, but not one per lifetime parameter of the struct, is an error. Error:
argument-count. - ref.lifetime.struct.holdsA lifetime struct holds a local reference (
ref.local.holding), so every rule of Local References applies to its values. - ref.lifetime.struct.positionEach lifetime parameter is one reference position of the struct's type, after the positions of its type arguments. A written lifetime argument names that position's lifetime (
ref.lifetime.position). - ref.lifetime.struct.constructA struct literal adds the origins of a field typed
&'a Tto the value's'aposition only. - ref.lifetime.struct.readReading a field typed
&'a Tgives a reference whose origins are the origins of the value's'aposition. - ref.lifetime.struct.read.one-lifetimeA field of another type whose reference positions all name one lifetime, as
Option[&'a T]orParser[T, 'a], is constructed and read the same way. - ref.lifetime.struct.read.mixedA field whose reference positions name two or more lifetimes, as
inner: Two['b, 'a], is constructed and read position by position: each position has the origins of the lifetime it names. A field nested inside such a field follows the same rule. - ref.lifetime.struct.field-elidedA field whose type names a lifetime struct without lifetime arguments holds a local reference, so it is an error. Error:
local-reference-escapes. - ref.lifetime.struct.elideA signature may name a lifetime struct without lifetime arguments. Each elided argument is a reference position that writes no lifetime (
ref.lifetime.position). - ref.lifetime.struct.elide.parameterIn a parameter's type, each elided argument has a lifetime of its own, so
p: &Parser[string]has two reference positions. - ref.lifetime.struct.elide.resultIn the result type, each elided argument takes its lifetime as
ref.lifetime.elidestates, as infn make(s: &string) -> Parser[string]. - ref.lifetime.struct.elide.ambiguousSo a result that writes no lifetime, with no reference receiver and two lifetimes among the parameters' positions, is an error, as in
fn src(p: &Parser[string]) -> &string. Error:ambiguous-reference-source. - ref.lifetime.struct.implAn inherent implementation's target may write the implementation's lifetimes, as in
impl[T, 'a] Parser[T, 'a]. Its methods'selfandSelfhave those lifetimes. - ref.lifetime.struct.impl.elidedAn implementation's target that names a lifetime struct without lifetime arguments is not checked yet, so it is an error. Error:
references-not-yet-checked. - ref.lifetime.struct.bodyA function body names a lifetime struct without lifetime arguments, as in
let p: Parser[string] = q.
struct Parser[T, 'src]:
src: &'src T
pos: usize
fn parser['a](src: &'a string) -> Parser[string, 'a]:
Parser { src: src, pos: 0 }
fn make(src: &string) -> Parser[string]: # the result takes src's lifetime
Parser { src: src, pos: 0 }
fn position(p: &Parser[string]) -> usize: # two lifetimes of its own
p.pos
impl[T, 'a] Parser[T, 'a]:
fn source(&self) -> &'a T:
self.src
fn length(text: string) -> usize:
p := parser(&text)
q := make(&text)
p.src.len() - position(&q) + q.source().len() # valid: text is in scope
struct Two['a, 'b]:
x: &'a string
y: &'b string
fn left['a, 'b](t: &Two['a, 'b]) -> &'a string:
t.x # valid: the `'a` position only
fn first(outer: string) -> usize:
let mut kept = &outer
if outer.len() > 0:
inner := "hello"
kept = left(&Two { x: &outer, y: &inner })
kept.len() # valid: kept does not point into innerWhy. These are Rust's struct lifetimes, as in
struct Parser<'a>. A lifetime struct has the representation of the same struct without lifetimes; only the checker tells its lifetimes apart. Elision is Rust's too:&Parser<'_, T>has two input lifetimes, so a result needs one named.
Note. Lifetime arguments elided in an implementation's target come in a later stage.
See also: Lifetime Parameters, Fields, Lifetime Enums.
#Lifetime Enums
A lifetime enum declares lifetime parameters, and its variants' payloads may hold local references of those lifetimes:
enum Token[T, 'src]:
Word(&'src T)
End
enum Pair['a, 'b]:
Left(&'a string)
Right(&'b string)
fn right['a, 'b](p: Pair['a, 'b], fallback: &'a string) -> &'a string:
match p:
Pair.Right(y) => y # error: local-reference-escapes
_ => fallback
fn count(fallback: &string) -> usize:
let mut t = Token.Word(fallback)
if fallback.len() > 0:
text := "hello"
t = Token.Word(&text)
match t: # error: local-reference-outlives-local
Token.Word(w) => w.len()
Token.End => 0- ref.lifetime.enumA top-level enum may declare lifetime parameters, as in
enum Token[T, 'src]. - ref.lifetime.enum.payloadA variant's payload field may write
&'a Tor&'a mut Twith one of the enum's lifetimes. Such a field is no escape to a field. - ref.lifetime.enum.typeA type names a lifetime enum as it names a lifetime struct:
ref.lifetime.struct.argument,.argument.count,.positionand.field-elidedapply. - ref.lifetime.enum.holdsA lifetime enum holds a local reference (
ref.local.holding), so every rule of Local References applies to its values. - ref.lifetime.enum.constructA variant construction adds the origins of a payload field typed
&'a Tto the value's'aposition only. - ref.lifetime.enum.matchA match binding of a payload field typed
&'a Thas the origins of the value's'aposition, since it is a copy of the payload (ref.match.copy). - ref.lifetime.enum.other-payloadA payload field of another type is constructed and bound as
ref.lifetime.struct.read.one-lifetimeand.read.mixedstate for a field. - ref.lifetime.enum.fn-valueA variant constructor as a function value has a result whose lifetimes take the payload's lifetime, as an elided result does (
ref.lifetime.struct.elide.result). SoToken.Wordis afn(&T) -> Token[T]. - ref.lifetime.enum.signatureA signature, an implementation's target and a function body name a lifetime enum without lifetime arguments as they name a lifetime struct:
ref.lifetime.struct.elideto.bodyapply.
enum Token[T, 'src]:
Word(&'src T)
End
fn word['a](t: Token[string, 'a], fallback: &'a string) -> &'a string:
match t:
Token.Word(w) => w
Token.End => fallback
fn make(src: &string) -> Token[string]: # the result takes src's lifetime
Token.Word(src)
impl[T, 'a] Token[T, 'a]:
fn or(self, fallback: &'a T) -> &'a T:
match self:
Token.Word(w) => w
Token.End => fallback
enum Pair['a, 'b]:
Left(&'a string)
Right(&'b string)
fn left['a, 'b](p: Pair['a, 'b], fallback: &'a string) -> &'a string:
match p:
Pair.Left(x) => x # valid: the `'a` position only
Pair.Right(_) => fallback
fn first(outer: string) -> usize:
let mut kept = &outer
if outer.len() > 0:
inner := "hello"
kept = left(Pair.Right(&inner), &outer)
kept.len() + word(make(&outer), &outer).len() # valid: kept does not point into innerWhy. These are Rust's enum lifetimes, as in
enum Token<'a>. A payload is a copy, so a match binding holds the payload's references with their origins, as reading a struct's field does.
See also: Variant Payloads.
#Lifetime Stores
A function may store a local reference into a place its caller owns when the place's type names the reference's lifetime:
struct User:
name: string
fn bad['a, 'b](seen: &mut List[&'a User], u: &'b User) -> void:
seen.push(u) # error: local-reference-escapes
struct Two['a, 'b]:
x: &'a string
y: &'b string
fn bad_x['a, 'b](t: &mut Two['a, 'b], s: &'b string) -> void:
t.x = s # error: local-reference-escapes
fn remember['a](seen: &mut List[&'a User], u: &'a User) -> void:
seen.push(u)
fn count(b: bool) -> usize:
let mut seen: List[&User] = []
if b:
local := User { name: "local" }
remember(&mut seen, &local)
seen.len() # error: local-reference-outlives-local- ref.lifetime.storeA store through a parameter's reference into a place the caller owns checks each reference position of the stored value against the lifetime that position of the place names. So
*t = Two { x: a, y: b }is valid witht: &mut Two['a, 'b],a: &'a stringandb: &'b string. A store into a field checks the field's positions only (ref.lifetime.store.field). The value in each position must depend only on what a result of that position's lifetime may depend on (ref.lifetime.return). Any other such store of a value that holds a local reference is an error (ref.dep.store). Error:local-reference-escapes. - ref.lifetime.store.collectionA list's
pushand a map's index assignment store their value into the list's or the map's place, soseen.push(u)followsref.lifetime.storewhenseenis such a parameter. - ref.lifetime.store.callA
&mutparameter whose referent has a reference position of a lifetime variable, asseen: &mut List[&'a T], is a place the call may store into. So the argument's place takes what the call's arguments in that lifetime's positions depend on, as for a type parameter (ref.generic.store). A referent with no reference position of its own that still holds references, asd: &mut S::ItemwithS < Shelf['a], is one position at its projection's lifetimes,'ahere. Soset(d, v)withfn set[T](dst: &mut T, x: T),*d = v, and a store into a field of*deach take avthat depends only on what a result of'amay depend on. Through a bound, a trait method's&mut Self::Itemparameter stands for the caller's place: withS < Mk[&'a Point],s.fill(d, v)storesvinto*dat'a. - ref.lifetime.store.argumentA type argument of a generic type may hold a local reference wherever the instance may hold one, by
ref.local.holding: in a function body, a parameter's type, and a function's result. A list and a map follow this rule as any generic struct does, soxs: List[&User]andseen: &mut List[&User]are valid parameter types. - ref.lifetime.store.elementA value read from a list or a map, as
seen[0]or the result ofget, has the origins of the collection's elements. - ref.lifetime.store.fieldA store into a field through such a reference, as
t.x = switht: &mut Two['a, 'b], checks each reference position of the field against the lifetime that position names. This holds at any depth, ast.inner.x = s, through a&mutof a part, asr := &mut t.innerthenr.x = s, and for a field of several lifetimes, as a field read does (ref.lifetime.struct.read.mixed). The value in each position must depend only on what a result of that position's lifetime may depend on. - ref.lifetime.store.field.callAt a call, each position of a
&mutargument's place takes only what the arguments in that position's lifetime depend on. So afterset_x(&mut t, &s),t's'aposition holdss's origins and its'bposition does not.
struct User:
name: string
fn remember[T, 'a](seen: &mut List[&'a T], u: &'a T) -> void:
seen.push(u) # u has 'a, as the list's elements do
fn index['a](by: &mut Map[string, &'a User], u: &'a User) -> void:
by[u.name] = u
fn set['a](out: &mut (&'a User), u: &'a User) -> void:
*out = u
struct Two['a, 'b]:
x: &'a string
y: &'b string
fn set_x['a, 'b](t: &mut Two['a, 'b], s: &'a string) -> void:
t.x = s # s has 'a, as x does
fn other(outer: string) -> usize:
let mut kept = &outer
if outer.len() > 0:
inner := "inner"
let mut t = Two { x: &outer, y: &outer }
set_x(&mut t, &inner)
kept = t.y
kept.len() # valid: t.y never held inner
fn total(a: User, b: User) -> usize:
let mut seen: List[&User] = []
remember(&mut seen, &a)
remember(&mut seen, &b)
let mut by: Map[string, &User] = {}
index(&mut by, &a)
seen[0].name.len() + seen[1].name.len() + by.len() # valid: a and b are in scopeWhy. This is Rust's
fn remember<'a>(seen: &mut Vec<&'a User>, u: &'a User): the place's type says which references it may hold, so the caller's list holds what the call stores, and its uses stay in their sources' scopes.
See also: Generic Calls, Local Scope.
#Generic Locality
The bound 'static marks a type parameter whose values may be kept past the call, because the type it stands for holds no local reference:
struct User:
name: string
fn keep[T < 'static](value: T) -> *mut T:
box(value) # valid: T holds no local reference
fn later[T < 'static](value: T) -> fn() -> T:
fn() -> T: value # valid: the capture holds no local reference
fn demo(u: User) -> string:
kept := keep(u) # User meets 'static
later(kept)().name- ref.generic.staticA type parameter bounded by
'static, as inT < 'staticorW < Display & 'static, stands only for a type that meets'static. - ref.generic.static.no-localA type meets
'staticwhen it holds no local reference other than a static reference, byref.local.holdingandref.local.holding.counted, and each type parameter it names is bounded by'static. A function type always meets it, since a closure captures no local reference. - ref.generic.static.errorAt a call, a written or inferred type argument that does not meet
'static, for a parameter bounded by it, is an error. Error:local-reference-escapes. - ref.generic.static.implAn implementation whose type parameter is bounded by
'staticapplies only where that parameter's argument meets'static, as for any other bound. - ref.generic.static.captureA closure's capture whose type names a type parameter must meet
'static. Error:local-reference-escapes. - ref.generic.static.no-fixNeither diagnostic has a fix-it.
- ref.generic.static.fn-conjunctionA generic callback that is kept past its call is bounded by both
'staticandFn(...). The bounds join with&in either order:F < 'static & Fn(A) -> RandF < Fn(A) -> R & 'staticare equivalent.
struct User:
name: string
fn later[T](value: T) -> fn() -> T:
fn() -> T: value # error: local-reference-escapes
fn hold[T < 'static](value: T) -> void:
pass
fn wrap(u: &User) -> void:
hold(box(u)) # error: local-reference-escapesWhy. This is Rust's
T: 'static. A function value carries no lifetime, so a value kept in one must hold no local reference. A counted reference carries its referent's, as Rust'sRc<&'a T>does.
#Static References
A static reference &'static T refers to a value that lives for the whole program and never changes. It is made from a top-level binding, a constant literal, or data the compiler places in static memory, and it reads like a &T:
struct Point:
x: i32
y: i32
let origin = Point { x: 3, y: 4 }
fn home() -> &'static Point:
&origin # valid: a top-level binding bound without `mut`
fn sum(p: &Point) -> i32:
p.x + p.y
fn demo() -> i32:
p := home()
let x: &'static i32 = &origin.x
let one: &'static i32 = &1
sum(p) + *x + *one # p coerces to &Point- ref.static.form
&'static Tis a static reference type. Its operand takes the forms of&T's, byref.type.forms, and it may be written wherever a&Tmay. - ref.static.distinct
&'static Tis distinct from&Tand from*T, and invariant inT. - ref.static.coerceA static reference coerces to
&Twhere a&Tis expected: an argument, a binding, a result, or the receiver of a&selfmethod. The&Tit gives depends on no local, so it may be returned from any function. - ref.static.place
&emakes a static reference wheneis a top-level binding bound withoutmut, or a struct or tuple field reached from one through no reference. - ref.static.literal
&emakes a static reference wheneis a constant literal: an integer, float, boolean, character, or string literal. The value lives in static memory, made once for the program. - ref.static.valueA parameter, a call result, or a binding of a static reference type is a static reference, as is a value the compiler places in static memory and gives that type.
- ref.static.source.errorAny other expression where a static reference is expected is an error. That covers
&of a local, a parameter, abox, alet muttop-level binding, or a call result. It covers&of a value reached through a*Tor a&T, or of a field of any of them. It covers a&Tor a*Tvalue too. Error:static-reference-source. - ref.static.source.messageThe diagnostic's message names the source and the three it may be. It has no fix-it.
- ref.static.no-mut
&'static mut Tis an error, since a source that can change would need a count. Error:static-reference-mut. - ref.static.not-localA static reference is not a local reference, so the rules of Local References do not hold for it. It may be stored in a field, an element, a box, or a top-level binding, and captured by any closure.
- ref.static.no-countMaking, copying, or ending a static reference changes no count. Neither does a read through one, including a read of a counted reference or a function value the referent holds: the referent holds it for the whole program.
struct Point:
x: i32
let origin = Point { x: 0 }
let mut moving = Point { x: 0 }
let shared: *Point = box(Point { x: 0 })
fn from_local() -> &'static Point:
p := Point { x: 1 }
&p # error: static-reference-source
fn from_mut() -> &'static Point:
&moving # error: static-reference-source
fn from_counted() -> &'static Point:
shared # error: static-reference-source
fn from_plain(p: &Point) -> &'static Point:
p # error: static-reference-source
fn writable(p: &'static mut Point) -> void: # error: static-reference-mut
passWhy. hd follows Rust's
&'static Tfor the type and its coercion to a shorter-lived&T. It follows Swift's immortal objects for the cost: a referent that is never freed needs no count, so a read through it takes no retain or release. Unlike Rust, hd has no&'static mut T, since Rust'sstatic mutisunsafeand a writable source would need a count. Rust promotes any constant expression; hd takes only a literal or a top-level binding, so the source is visible where it is written.
#Lifetime Bounds
A type parameter bounded by a declared lifetime stands for a type whose values may hold local references of that lifetime, so a struct may store a closure that captures one:
use std.function.FnMut
struct Counter:
n: i32
struct Button[F < FnMut() -> void & 'a, 'a]:
on_click: F
fn press[F < FnMut() -> void & 'a, 'a](mut b: Button[F, 'a]) -> void:
(b.on_click)()
fn bump(c: &mut Counter) -> void:
b := Button { on_click: fn(): c.n += 1 } # captures the local reference c
press(b)
fn twice[F < FnMut() -> void](mut f: F) -> void:
f()
f()
fn bump_twice(c: &mut Counter) -> void:
twice(fn(): c.n += 1) # captures c for the call
struct Plain[F < FnMut() -> void]:
on_click: F
fn click(c: &mut Counter) -> void:
let mut p = Plain { on_click: fn(): c.n += 1 } # p holds c
(p.on_click)()
struct Shift:
offset: i32
impl Shift:
fn apply(&self, xs: List[i32]) -> List[i32]:
xs.iter().map(fn(x: i32) -> i32: x + self.offset).collect() # the adapter holds self- ref.generic.outlivesA type parameter may be bounded by one lifetime that is in scope, as in
F < FnMut() -> void & 'a. Its argument may hold local references of that lifetime. - ref.generic.outlives.oneA second lifetime bound on one type parameter is not checked yet, so it is an error. Error:
references-not-yet-checked. - ref.generic.outlives.fieldA struct literal may give a function value with captured origins to a field whose type is a type parameter that
'staticdoes not bound. A closure written there may capture local references. The struct value holds the captured origins in that parameter's positions, asref.generic.outlives.instancestates. Error:local-reference-escapes. - ref.generic.outlives.positionA field whose type parameter has a lifetime bound lies in that lifetime's position. A literal adds the closure's captured origins to that position, and reading the field gives a function value with that position's origins.
- ref.generic.outlives.readA function value with captured origins follows
fn.capture.local-usesandfn.capture.local-store. Returning it where the result has no source for those origins is an error. Error:local-reference-escapes. - ref.generic.outlives.boxBoxing a function value with captured origins, or passing it for a type parameter bounded by
'static, is an error. Error:local-reference-escapes. - ref.generic.outlives.read-onlyA store through a captured
&mutreference, asc.n += 1above, changes a capture. Such a closure needs anFnMutbound, asfn.trait.read-onlystates. Error:not-writable. - ref.generic.outlives.argumentA closure written as a call argument for a parameter of a bare type parameter
F, asmut f: F, may capture local references. The callee's signature must not nameFinside a function type or an opaque type, and'staticmust not boundF. Error:local-reference-escapes. - ref.generic.outlives.argument-originsThe call's result holds the captured origins in
F's positions, asref.generic.callstates. A lifetime bound onFputs them in that lifetime's positions too. - ref.generic.outlives.instanceA function type that a type argument puts inside another type, as
FinMapIter[I, T, U, F]orPlain[F], is a position of that type. It holds what its closure captured, so a result such asxs.iter().map(...)carries the captures and followsref.generic.outlives.read. - ref.generic.outlives.writtenA function type written inside another type of a parameter, as in
Option[fn() -> void]orMapIter[ListIter[i32], i32, i32], holds no captured origins. Passing a value whose function value there captures local references is an error. Error:local-reference-escapes.
struct Plain[F < FnMut() -> void]:
on_click: F
struct Label[F < Fn() -> void & 'a, 'a]:
on_show: F
fn view['a, 'b, T < 'a & 'b](value: T) -> void: # error: references-not-yet-checked
pass
fn plain(flag: bool) -> void:
let mut p = Plain { on_click: fn(): pass }
if flag:
let mut inner = Counter { n: +2 }
r := &mut inner
p = Plain { on_click: fn(): r.n += 1 }
(p.on_click)() # error: local-reference-outlives-local
fn show(c: &mut Counter) -> void:
l := Label { on_show: fn(): c.n += 1 } # error: not-writable
fn keep(c: &mut Counter) -> void:
b := Button { on_click: fn(): c.n += 1 }
kept := box(b.on_click) # error: local-reference-escapes
fn make() -> fn() -> void:
let mut x = Counter { n: +0 }
r := &mut x
b := Button { on_click: fn(): r.n += 1 }
b.on_click # error: local-reference-escapes
fn wrap[F < FnMut() -> void](f: F) -> Plain[F]:
Plain { on_click: f }
fn same[F < FnMut() -> void](f: F) -> F:
f
fn first[F < Fn() -> i32 & 'a, 'a](c: &'a Counter, f: F) -> &'a Counter:
c
fn nested(c: &mut Counter) -> Plain[fn() -> void]:
wrap(fn(): c.n += 1) # error: local-reference-escapes
fn escape() -> fn() -> void:
let mut x = Counter { n: +0 }
r := &mut x
same(fn(): r.n += 1) # error: local-reference-escapes
fn pick(outer: &Counter) -> i32:
let mut r: &Counter = outer
if outer.n > 0:
inner := Counter { n: +2 }
p := &inner
r = first(outer, fn() -> i32: p.n)
r.n # error: local-reference-outlives-localWhy. This is Rust's
F: FnMut() + 'a. Afn(...)type carries no lifetime, so the struct's lifetime holds what its closure captures. A closure argument for a bareFis Rust's inferred closure lifetime: the call's result carries its captures, also inside an adapter such asMap<I, F>. A struct literal infersFas such a call does. Afn(...)type written in a parameter's type is Rust's function pointer, which captures nothing.
See also: Static Fn Bounds, Lifetime Structs.
#Generic Calls
A type argument may hold a local reference, so a generic function or method works on references as on any other value:
struct User:
name: string
struct Pair:
left: User
right: User
fn id[T](value: T) -> T:
value
fn left_or_right(pair: &Pair, left: bool) -> &User:
let o: (&User)? = if left: .Some(&pair.left) else: .None
o.unwrap_or(&pair.right) # borrows from pair
fn demo(u: &User) -> usize:
n := id(&u.name) # n borrows from u
n.len()- ref.generic.localA written or inferred type argument of a function, a method, or an implementation may hold a local reference.
- ref.generic.local.local-functionA type argument of a local function never holds one yet. Error:
local-reference-escapes. - ref.generic.callA reference position that a type argument adds to a call's result depends on the argument positions that the same type parameter adds to the call's parameters at the same position of the type argument, as a lifetime variable's positions do (
ref.lifetime.call). It depends on no other argument. Withfn pick[T](x: T) -> TandT = (&'a A, &'b B),pick(t)._0depends ont._0and not ont._1. A position the type parameter adds to no argument depends on nothing. A type argument with no reference position of its own that still holds references, as a projectionS::Itemdoes, passes them whole: a result of typeT, as offn id[T](x: T) -> T, holds what the argument forTheld, and no lifetime elides to it (ref.dep.elide). Through a bound that fixes the type argument, asS < Put[T::Item], the argument is at that type's lifetimes. - ref.generic.call.line-upEach argument lines up with its parameter's type instantiated at the call. A trait value given for
&Tlines up with that reference, and a position of a projection such asP::Outis a position ofP. - ref.generic.storeA parameter
&mut P, whosePnames a type parameter, is a place the call may store into. So the argument's place takes what that type parameter's other argument positions depend on, as*p = vdoes (ref.dep.store). - ref.generic.bodyA generic body treats a value of a type parameter as one that may hold a local reference: it may return it or pass it on, and keeps it past the call only under
'static.
struct User:
name: string
struct Holder[T]:
value: T
fn id[T](value: T) -> T:
value
fn put[T](h: &mut Holder[T], value: T) -> void:
h.value = value
fn bad_id(u: &User) -> &string:
local := User { name: "x" }
id(&local.name) # error: local-reference-escapes
fn bad_put(u: &User) -> usize:
let mut h = Holder { value: u }
if u.name.len() > 0:
local := User { name: "y" }
put(&mut h, &local)
h.value.name.len() # error: local-reference-outlives-local
fn bad_store(h: &mut Holder[&User], u: &User) -> void:
put(h, u) # error: local-reference-escapes
fn bad_local(u: &User) -> void:
fn same[T](value: T) -> T:
value
_ := same(u) # error: local-reference-escapesWhy. This is Rust's model: a type argument's lifetimes travel with it, so a call's result borrows what its arguments in that parameter's positions borrow.
#Reading Through A Reference
Field access and method calls read through a reference automatically, and *r reads the whole value.
struct Vec2:
x: f64
y: f64
impl Vec2:
fn len2(self) -> f64:
self.x * self.x + self.y * self.y
fn demo(r: &Vec2) -> f64:
copy := *r # a copy of the whole value
r.x + r.len2() + copy.y- ref.read.autoA field read or a method call on a reference applies to the value it refers to:
r.xreads the fieldxof that value, andr.len2()callslen2on it. - ref.read.auto.levelsThe read goes through every reference level,
&,&mut,*, and*mutalike: withx: &*mut User,x.namereads(*(*x)).name, andx.describe()callsdescribeon theUser. - ref.read.auto.method-levelA method call stops at the first level whose referent has the method itself, as Rust's auto-deref does: with
x: &*Tand animpl Display for *T,x.to_string()calls that impl's method. - ref.read.auto.writeA field write or a
&mut selfcall through several levels needs only the last level to be writable, as(*x).f = vdoes byref.read.shallow:x.age = 1is valid withx: &*mut Userand an error withx: &mut *User. Error:not-writable. - ref.read.auto.explicitOnly field access and method calls read through every level. A condition, a cast, a range bound,
?, a spread, and a call of a function value keep an explicit*. - ref.deref.read
*rreads the whole valuerrefers to. The result is a copy. - ref.deref.kinds
*rreads through a counted and a local reference alike. - ref.deref.not-reference
*eon a value that is not a reference is an error. Error:type-mismatch. - ref.read.typeA read through a writable reference,
*mut Tor&mut T, has typeT, and the value it reaches is a writable place. - ref.read.shallowA read through a read-only reference,
*Tor&T, keeps its declared type; the reference makes only the value it refers to read-only. - ref.read.index.declaredAn index on a reference to a list, map, or string reads an element of the referenced value.
With Team { name: string, lead: *mut User } and t: &Team:
| Expression | Result |
|---|---|
t.name = "x" |
Error: not-writable; the referenced value is read-only. |
t.lead.age = +1 |
Valid; lead retains *mut User. |
t.lead.birthday() |
Valid for a &mut self method. |
x := t.lead |
x has type *mut User. |
*t |
A copy of type Team, with its declared field types. |
struct User:
age: i32
struct Team:
name: string
lead: *mut User
fn copy(t: &Team) -> Team:
*t
fn dup[T](t: &T) -> T:
*t
fn edit(t: &Team) -> void:
x := t.lead
x.age = +1#Matching Through A Reference
A pattern that tests a value reads through a reference, as a field access does, so a recursive enum is matched through its * links.
enum Expr:
Num(n: i64)
Add(left: *Expr, right: *Expr)
fn eval(e: &Expr) -> i64:
match e:
.Num(n) => n
.Add(.Num(a), r) => a + eval(r)
.Add(l, r) => eval(l) + eval(r)- ref.match.readA variant, tuple, data, literal, or range pattern matched against a reference of either kind,
*T,*mut T,&T, or&mut T, matches the value the reference refers to. - ref.match.nestedThe rule applies at every depth: a nested pattern reads through a payload field, a tuple element, or a struct field of reference type.
- ref.match.bindingA binding or
_matched against a reference takes the reference itself, sowhole => whole is eistrue. - ref.match.copyA copied payload or field that a pattern binds below such a read is a copy of it, read at the time of the match.
- ref.match.declared-typeA binding copied by a pattern through a reference keeps its declared type.
- ref.match.borrowBelow a
&Tor&mut T, a pattern binds a payload or field whose type is not copied as a reference to it. The binding has type&Fbelow a&T, and&mut Fbelow a&mut Twith no&above it. Error:type-mismatchwhere anFis expected. - ref.match.borrow.exclSuch a binding is a reference to the matched place, like
&*ror&mut *r.ref.excl.mutandref.excl.sharedapply to it while it is live. Error:conflicting-access.
enum Holder:
Empty
Cell(value: *mut i64)
fn reset(h: &Holder) -> void:
match h:
.Cell(value) =>
*value = 0
.Empty => passstruct Photo:
width: i32
impl !Copy for Photo
enum Slot:
Empty
Full(Photo)
fn widen(r: &mut Slot) -> void:
match r:
.Full(p) => p.width += 1 # p: &mut Photo
.Empty => passWhy. A copied binding is a value, so a later write to the matched place does not change it. A payload that is not copied cannot be read out of a place behind a reference, so the pattern lends it instead, and the exclusivity rules keep the enum's variant fixed while the loan is live.
See also: Payload Bindings, Exhaustiveness.
#Writing Through A Reference
*r = v replaces the value r refers to, and a field assignment through a writable reference writes the referenced value's field.
struct Point:
x: i32
y: i32
fn reset(r: &mut Point) -> void:
*r = Point { x: 0, y: 0 }
r.x += 1- ref.deref.write
*r = vand*r op= vreplace the valuerrefers to.rmust be a writable reference,*mutor&mut. Error:not-writable. - ref.write.fieldAssigning a field through a reference, as in
r.x = v, writes the field of the referenced value. The reference must be a writable one,*mutor&mut. Error:not-writable. - ref.write.seenThe write is seen through every reference to the place, and through the place itself.
- ref.write.no-exclusivityA counted writable reference,
*mut T, is not exclusive: other references to the same place may exist and be used. A&mut Tis exclusive while it is live, as Writes While Borrowed states. - ref.write.indexAn element store through a reference to a list or a map, as in
r[i] = vorr[i] op= v, stores into the referenced value. A change of that value through a method call, as inr.push(x), changes it in place as well. The reference must be a writable one,*mutor&mut. Error:not-writable.
struct Point:
x: i32
y: i32
fn invalid(r: &Point) -> void:
*r = Point { x: 0, y: 0 } # error: not-writable
r.x = 1 # error: not-writableWhy. A counted reference never dangles, so a write through another path cannot free what a reference reads; exclusivity would forbid only aliasing that is safe.
#Identity
r is s is true when the references r and s refer to the same place.
@derive(Eq)
struct Point:
x: i32
y: i32
fn demo() -> bool:
p := Point { x: 1, y: 2 }
q := Point { x: 1, y: 2 }
r := &p
s := &p
t := &q
r is s && !(s is t) && *s == *t- ref.identity.same-place
r is swith two references is true when both refer to the same place, and false otherwise. Two places that hold equal values are different places. - ref.identity.placesTwo references refer to the same place when they start at the same root and read the same struct fields from it. A root is one execution of a local's declaration, one call's parameter, a top-level binding, or one new object.
- ref.identity.copiesA copy of a reference, a reference converted to another kind or to read-only, and a reference passed to or returned from a function refer to the place the original refers to. So do
&*rand&mut *r. - ref.identity.mutability
iscompares references of either kind and either mutability, such as a&Twith a*mut T, since all may refer to one place. - ref.identity.incompatible
isbetween references to different types is an error. Error:incompatible-identity-operands. - ref.identity.non-reference
isbetween a reference and a value without identity, such as a struct, is an error. Error:identity-requires-references. - ref.identity.valuesA struct, tuple, or enum value has no identity, even when it holds references, so
ison one is an error. Error:identity-requires-references. - ref.identity.optionalAn optional reference,
*T?, holds one reference or none. The reference matched out of.Some(r)refers to the placerrefers to.
struct Point:
x: i32
fn same(a: &i32, b: &i64, p: &Point, v: Point) -> void:
one := a is b # error: incompatible-identity-operands
two := p is v # error: identity-requires-referencesWhy. A counted reference in hd never dangles, so code may keep one in a field or a list. Code that keeps references needs to ask whether two of them are the same object, as a graph walk or an observer list does;
isanswers without reading the values.
#Equality Of References
== between two counted references is an error, because is and *r == *s
say which comparison is meant. Between two local references it compares
values.
- ref.identity.no-equality
==and!=with two counted reference operands, of types*Tor*mut T, are an error. Error:reference-equality. - ref.identity.no-equality.fixThe diagnostic has two fix-its: one writes
r is s, or!(r is s)for!=, and compares places; the other writes*r == *s, or*r != *s, and compares values. - ref.identity.generic-eqA reference type implements
Eqwhen its value type does, andHashwhen its value type does. They compare and hash the values the references refer to, as Reference Equality states. So generic code and a derivedEqcompare through references. - ref.identity.local-equality
==and!=with two local reference operands, of types&Tor&mut T, compare the values they refer to, byexpr.op.ref-read.equal-values.
fn same(a: *i32, b: *i32) -> bool:
a == b # error: reference-equality
fn equal(a: &i32, b: &i32) -> bool:
a == b # valid: compares the valuesWhy. Go's
==on pointers compares addresses, and Rust's compares contents. A counted reference is a shared object, where an author from either language would guess wrong half the time, so neither guess compiles. A local reference lends a value to one call, so it compares as that value, as in Rust.
See also: Derived Implementations, Identity.
#Element References
&xs[i] and &mut xs[i] refer to the slot i of the list xs, and &m[k] and &mut m[k] to the value of the key k in the map m. An element reference lives until its last use, including when a binding or dependent result holds it.
struct Player:
name: string
score: i32
fn reward(player: &mut Player, points: i32) -> void:
player.score += points
fn rewarded(players: List[Player], best: usize) -> List[Player]:
let mut out = players
reward(&mut out[best], 10) # changes out[best] during the call
out[best].score += 1 # the element is a place without a reference too
out.push(Player { name: "new", score: 0 }) # the call's access has ended
out- ref.elem.place
&xs[i]and&mut xs[i], wherexsis a list, are element references: they refer to the slotiof the list. A struct field read from the element extends the place, as in&mut xs[i].pos, and an element of an inner list is a slot of that list, as in&mut grid[r][c]. - ref.elem.map
&m[k]and&mut m[k], wheremis a map, are element references too: they refer to the value of the keykinm. Each rule of this section holds for them, with the key in place of the index. - ref.elem.indexThe index is evaluated and checked once, when the reference is taken. An index that is not less than the list's length is a checked runtime panic. Panic:
index-out-of-bounds. - ref.elem.map.keyA key that the map does not hold is a checked runtime panic when the reference is taken, as a read of
m[k]is. Panic:index-out-of-bounds. - ref.elem.slotAn element reference names a slot, never the value in it. A read through it sees whatever value its slot holds, and a write replaces that value. After elements move between slots, as a sort or a swap moves them, it sees the element in its slot.
- ref.elem.writable
&mut xs[i]needsxsin a writable place, as an element store does (types.coll.writable.store). Its fix-it makes the binding writable. Error:not-writable. - ref.elem.writable.shared
&xs[i]needs no writable place, so it may refer into a:=list or a value parameter. - ref.elem.through-reference
xsmay be a reference to a list:&r[i]and&mut r[i]refer to the slotiof the listrrefers to. Through a read-only reference,*Tor&T,&mut r[i]is an error. Error:not-writable. - ref.elem.identityTwo element references refer to the same place when they refer to the same slot of the same list's elements and read the same struct fields from it.
- ref.elem.trait-accessorsA reference returned by
Index.indexorIndexMut.index_mutis an element reference and follows the same lifetime and access rules as a built-in element reference.
fn bump(score: &mut i32) -> void:
*score += 1
fn invalid() -> void:
xs := [+1, 2]
bump(&mut xs[0]) # error: not-writableWhy. A list grows by moving its elements. Go keeps the old array alive, so a write through an old pointer silently stops reaching the slice. An element reference instead holds its collection while it lives, so nothing can move or detach its slot. A handle that survives a sort is a reference stored in the list,
List[*mut Player], or an ID.
#Call-Scoped Access
An element reference is a local reference value. Its collection's length holds still until the reference's last use.
fn bump(score: &mut i32) -> void:
*score += 1
fn record(scores: &mut List[i32], score: &mut i32) -> void:
scores.push(*score)
fn demo() -> void:
let mut scores = [+1, 2]
bump(&mut scores[0]) # valid: the access ends after this use
record(&mut scores, &mut scores[0]) # error: conflicting-access
best := &mut scores[1]
scores.push(3) # error: conflicting-access
n := scores.len() # error: conflicting-access
scores[0] = 5 # valid: a store to another element
*best += 1
scores.push(4) # valid: after best's last use- ref.elem.local-valueAn element reference is a local reference value. It may be bound, assigned, passed, and used as the source or result of a dependent call, subject to every rule of Local References and Dependent Results.
- ref.elem.access.liveThe reference's access to its collection begins when the reference is taken and ends after its last use.
- ref.elem.access.live-lengthWhile an access lasts, nothing may change the collection, or a place that holds it, other than by a store to one of its elements. Reads of the collection, and stores to its elements, the referenced one included, stay valid.
- ref.elem.access.lengthWhile a binding that holds an element reference is live (
ref.excl.live), a change of its collection or of a place that holds it is an error, and so is a&mutof another element of it. Error:conflicting-access.- The collection is a place that
ref.excl.placecovers, so it may be reached through a&mutparameter. - Such a change is a call that takes
&mutof the collection or of a place that holds it, aspush,insert,remove_at,pop,clearandreservedo, or an assignment of a whole value to it, as inxs = []. - A map's
removeis one, and so is a map store of a key other than the referenced one. - Two keys are one key when both are one constant or reads of one
:=binding.
- The collection is a place that
- ref.elem.access.mutWhile a binding that holds a
&mutelement reference is live, any use of its collection or of a place that holds it is an error: a copy, a&of it, alen()or another method call. So is any other reference into the collection,&or&mut, at any index. A read of another element or a store to one stays valid. Error:conflicting-access. - ref.elem.unaliasedA collection is unaliased when it is a local binding or a value parameter, or a struct field or element reached from one through no reference.
- ref.elem.conflictDuring an access to an unaliased collection, another argument or the receiver of the same call that may change the collection, or a later argument that moves it (
ref.excl.move), is an error. For a&mutelement reference, so is another argument that refers into the collection, and a later argument that uses it (ref.elem.access.mut). Error:conflicting-access.- The collection may also be a place that
ref.excl.placecovers, so one reached through a&mutparameter, as inchange(list, &mut list[2]). - An argument that holds an element reference is an access, whether the call takes the reference or a binding holds it, as in
grow(&mut xs, first)afterfirst := &xs[0].
- The collection may also be a place that
- ref.elem.access.aliasWhere a
*Tor a variable a closure shares reaches the collection, the element reference holds that object as Conflicts Through Aliases says, so a change through another path panics. Panic:borrow-conflict.
An argument may change the collection's length when it does one of the following to the collection, or to a place that holds it:
| Rule | The argument or receiver | Example |
|---|---|---|
| ref.elem.conflict.referenceReference | takes &mut of it |
record(&mut scores, &mut scores[0]) |
| ref.elem.conflict.methodMethod call | calls a &mut self method on it |
place(&mut scores[0], scores.remove_at(1)) |
Why. This is Swift's Law of Exclusivity, and for a
&mutelement reference Rust's borrow rules. A conflict is caught at compile time where every path to the collection is in view, and by a pointer loan where a pointer or a shared variable may reach it. Stores to other elements cannot move the referenced slot, so they stay legal.
See also: Element Reference Loops, Collection Values, Map Values.
#Captured References
A closure that captures a counted reference copies the reference, so the closure and its scope refer to the same place:
struct Point:
x: i32
y: i32
fn bump(p: *mut Point) -> fn() -> void:
fn() -> void: p.x = p.x + 1
fn demo() -> i32:
origin := box(Point { x: 0, y: 0 })
step := bump(origin)
step()
step()
origin.x- ref.capture.copyCapturing a counted reference copies the reference. The copy and the original refer to the same place, as any two copies of a reference do (
ref.place.alias). - ref.capture.write-throughA write through a captured
*mut Tchanges the place it refers to, and every other path to that place sees the write. - ref.capture.variableA captured
letvariable that holds a counted reference is shared like any variable. Assigning it another reference changes the place that the closure and its scope both use.
Why. A reference already names a place, so copying it shares that place.
- ref.capture.local-scopedA closure supplied directly for a function parameter may capture a local reference under
ref.local.capture-parameter. - ref.capture.local-storedAny other closure capture of a local reference is an error under
ref.local.escape.capture-stored.
See also: Copied And Shared Captures,
ref.read.shallow.
#Moves
A &mut T value is never copied. A binding that gives its value away moves it, and the binding may not be used again until it is assigned. A call that expects &mut reborrows the binding instead: it lends what the binding refers to for the call.
struct Counter:
count: i32
fn bump(c: &mut Counter) -> void:
c.count += 1
fn keep[T < ?Copy](x: T) -> void: pass
fn demo(c: &mut Counter) -> void:
bump(c) # a reborrow: c stays usable
bump(c)
keep(&mut *c) # an explicit reborrow
d := c # c moves into d
bump(d)- ref.move.mutA
&mut Tvalue is moved, not copied. A*mut Tor&Tvalue is copied. - ref.move.holdsA value whose type holds a
&mutis moved, not copied. A type holds a&mutwhen it is&mut T, or when a struct's field, an enum's payload, a newtype's base, or a tuple's, optional's, or union's member holds one.SpanMut[T, 'a]holds one. Copy names the other types whose values move. - ref.move.sitesA read of a whole binding that is not copied moves its value at each site in the table below. No
&muttype is expected at these sites. - ref.move.fieldA read of a field of a binding, where the field's type is not copied, moves the field out at each site in the table below. The binding is then partly moved. A site that expects a
&muttype reborrows the field instead, as for a binding. A field of a field moves the same way. - ref.move.patternA
matcharm orletpattern that binds a value whose type is not copied moves that value out of the matched value. When the matched value is a binding, or a field of one, a bound payload or field moves out as a field does. The binding is then partly moved. A_pattern moves nothing, and neither does binding only copied parts. A pattern matched through a reference binds as Matching Through A Reference states. - ref.move.out-of-placeA read of a value that is not copied, from a place behind a
&T,&mut T,*Tor*mut T, is an error at each site in the table below. Such a place is*r, or a field reached throughr, such asr.target. A site that expects a&muttype reborrows instead. Error:move-out-of-place. - ref.move.out-of-place.captureA read of a value that is not copied, from a binding the enclosing closure captures or a field of it, is an error at each site in the table below, since the closure may be called any number of times (
fn.capture.call.any). Borrowing the binding and calling a&selfmethod on it read nothing out. Error:move-out-of-place. - ref.move.reborrowAn argument whose parameter is declared
&mut Treborrows the binding for the call and does not move it. A&mut selfreceiver is such an argument. - ref.move.reborrow.explicit
&mut *rreborrowsrexplicitly. It makes a new&mutto the placerrefers to, andrstays usable. - ref.move.reborrow.typedA site that expects a written
&mut Ttype reborrows the value instead of moving it. These sites are aletthat writes the type, an assignment to a place of a&muttype, and a struct field or variant payload declared&mut. Only a&mutvalue reborrows: a value of another type that is not copied moves at aletthat writes its type, at an assignment, and into a field. - ref.move.reborrow.sharedConverting a
&mut Tvalue to&T, as inlet t: &T = r, reborrows it as a shared reference and does not move it. - ref.move.reborrow.exclA reborrow that a
let, an assignment, a field or a payload keeps is a reference to the placerrefers to, like&mut *ror&*r.ref.excl.mutandref.excl.sharedapply to it while it is live. An argument's reborrow lasts asref.excl.callstates, sobump(c); bump(c)is valid. Error:conflicting-access. - ref.move.useA use of a binding whose value moved on some path to the use is an error. The path may run through an earlier iteration of a loop. Error:
use-of-moved-value. - ref.move.use.partialA use of a partly moved binding is an error when it reaches a moved field: a use of the whole binding, of the moved field, or of a place inside that field. Its other fields stay usable. A moved payload counts as a moved field, so matching the binding again is such a use. Error:
use-of-moved-value. - ref.move.use.formsA use is a read of the binding or of a place through it, a write through it, a reference to it, or a closure that captures it. A closure captures the whole binding.
- ref.move.reassignAssigning the binding a new value makes it usable again. Assigning a moved field a new value makes that field usable again, and the binding whole when no other field is moved.
| Site | Example |
|---|---|
A := binding, or a let without a written type |
d := c, let d = c |
An argument for a parameter not declared &mut, such as a T < ?Copy |
keep(c) |
| A tuple element, a list element, or an optional's payload | (c, 1), .Some(c) |
| A struct field or variant payload whose declared type is a type parameter | Wrap { value: c } |
A returned value, or the value of a break |
return c |
struct Counter:
count: i32
fn bump(c: &mut Counter) -> void:
c.count += 1
fn keep[T < ?Copy](x: T) -> void: pass
fn after_let(c: &mut Counter) -> void:
d := c
bump(c) # error: use-of-moved-value
fn after_generic(c: &mut Counter) -> void:
keep(c)
c.count = 1 # error: use-of-moved-value
fn after_branch(c: &mut Counter, early: bool) -> void:
if early:
keep(c)
bump(c) # error: use-of-moved-value
fn in_loop(c: &mut Counter) -> void:
for i in 0..3:
keep(c) # error: use-of-moved-value
fn after_typed_let(c: &mut Counter) -> void:
let d: &mut Counter = c
c.count = 1 # error: conflicting-access
d.count += 1struct Holder['a]:
target: &'a mut i32
count: i32
fn take(h: Holder) -> void:
pass
fn moved(x: &mut i32) -> void:
h := Holder { target: x, count: 1 }
t := h.target # moves the field out
n := h.count # another field stays usable
take(h) # error: use-of-moved-value
fn demo(x: &mut i32, y: &mut i32) -> void:
let mut h = Holder { target: x, count: 1 }
t := h.target
h.target = y # h is whole again
take(h)struct Holder['a]:
target: &'a mut i32
fn take(h: Holder) -> void:
pass
fn twice(x: &mut i32) -> void:
let o: Holder? = .Some(Holder { target: x })
match o:
.Some(h) => take(h) # moves the payload out of o
.None => pass
match o: # error: use-of-moved-value
.Some(h) => take(h)
.None => pass
fn refill(x: &mut i32, y: &mut i32) -> void:
let o: Holder? = .Some(Holder { target: x })
match o:
.Some(_) => pass # `_` moves nothing
.None => pass
let .Some(h) = o else: return
take(h)
o = .Some(Holder { target: y }) # o is whole again
match o:
.Some(g) => take(g)
.None => passstruct Holder['a]:
target: &'a mut i32
count: i32
fn peek(h: &Holder) -> i32:
h.count
fn keep[T < ?Copy](x: T) -> void: pass
fn twice['a, 'b](r: &'b Holder['a]) -> (Holder['a], Holder['a]):
(*r, *r) # error: move-out-of-place
fn whole(r: &mut Holder) -> i32:
n := (*r).count # an i32 is copied
keep(*r) # error: move-out-of-place
peek(&*r) + peek(r)
fn field(r: &mut Holder) -> void:
t := r.target # error: move-out-of-place
let u: &mut i32 = r.target # a reborrowstruct Photo:
width: u32
impl !Copy for Photo
struct Pair:
a: Photo
fn shared(r: *Pair) -> Photo:
r.a # error: move-out-of-place
fn mutable(r: *mut Pair) -> Photo:
r.a # error: move-out-of-place
fn copied(r: *Pair) -> Photo:
Photo { width: r.a.width } # a new value from copied fieldsWhy. A reference lends a place but does not own the value there. Moving a value that holds a
&mutout of it would leave two values that write one place. Rust reports the same read as "cannot move out of*r" (E0507). Borrow the place with&*ror&mut *r, or passron. A counted reference shares its object, so the other references to it still read the field. Rust'sRcrefuses the same move (E0507).
Why. This is Rust's rule (E0382) for
&mut. Two copies of one&mutwould both write the same place, which the exclusivity rules forbid. The implicit reborrow keeps the common case,bump(c); bump(c), valid.
A value that holds a &mut moves the same way. Its &mut self methods
borrow it for the call, as with any let mut binding:
use std.collections.SpanMut
fn spans(items: &mut List[i32]) -> void:
let mut span = items.span_mut()
span.swap(0, 1) # a `&mut self` receiver: span stays usable
let mut part = span # span moves into part
part.fill(0)
span.fill(1) # error: use-of-moved-valueWhy. Rust's rule: a type is
Copyonly when all its fields are, and&mut Tis not. Copying a span would give two views that write one list.
See also: Writes While Borrowed.
#Copy
Copy is the prelude's marker for a type whose values are copied. Every
type is Copy unless it holds a &mut, is declared impl !Copy, or is a
type parameter declared ?Copy. A value of any other type moves.
struct Photo:
width: u32
pixels: List[u8]
impl !Copy for Photo
fn keep[T](x: T) -> void: pass
fn hold[T < ?Copy](x: T) -> T: x
fn export(photo: Photo) -> Photo:
keep(photo.width) # a `u32` is copied
hold(photo) # photo moves- ref.copy.marker
Copyis a sealed marker trait thatstd.coredeclares andstd.opsre-exports, in the prelude. It has no members, and the compiler supplies its implementations. - ref.copy.structureA type is
Copyunless it is&mut T, a type declaredimpl !Copy, a type parameter that is notCopy, or a type that holds one in a field, payload, member, or newtype base (ref.move.holds). - ref.copy.movesA value whose type is not
Copyis moved, not copied, at each site ofref.move.sites. - ref.copy.opt-out
impl !Copy for Tdeclares that the struct, enum, or newtypeTis notCopy. It has no body and belongs in the module that declaresT. A type with aDropimplementation must not beCopyin any instance (module.rt.drop.not-copy). - ref.copy.opt-out.invalidA negative implementation of a trait other than
Copy, of a type that is not a struct, an enum, or a newtype, outside its target's module, or with a body is an error. Error:invalid-negative-impl. - ref.copy.no-impl
impl Copy for Tis an error, as for every sealed trait. Error:sealed-trait-implementation. - ref.copy.generic.defaultEvery type parameter is
Copyunless it is declared?Copy: a function's, a method's, a struct's, an enum's, an alias's, an implementation's, and a trait's. - ref.copy.generic.argumentA type argument for a
Copyparameter must beCopy. This holds for the inferred arguments of a call, a struct literal, and a variant construction. Error:unsatisfied-trait-bound. - ref.copy.generic.relaxed
T < ?Copylifts the default bound.Tthen accepts every type, and the body moves aTvalue as one that is notCopy. - ref.copy.generic.relaxed.onlyA
?before a trait other thanCopyis an error. Error:invalid-relaxed-bound. - ref.copy.trait.defaultA trait's
SelfisCopy, so a bound on the trait impliesCopy. An implementation for a type that is notCopyis an error. Error:missing-supertrait-implementation. - ref.copy.trait.referenceA
&mut dynvalue meets no bound on a trait whoseSelfisCopy. Error:unsatisfied-trait-bound. - ref.copy.trait.relaxed
trait Name < ?Copylifts theCopybound onSelf. A type that is notCopymay implement the trait, and its default bodies moveSelf.Index,IndexSet, andInspectableare declared so. - ref.copy.collections
List,Map,Set,Deque, andHeapholdCopyitems. A list or map literal whose items are notCopyis an error. Error:unsatisfied-trait-bound.
struct Photo:
width: u32
struct Writer['a]:
target: &'a mut List[i32]
struct Holder['a]:
target: &'a mut i32
impl !Copy for Photo
impl !Eq for Photo # error: invalid-negative-impl
trait Sized2D:
fn area(&self) -> u32
impl Sized2D for Photo: # error: missing-supertrait-implementation
fn area(&self) -> u32: self.width
fn keep[T < ?Copy](photo: T) -> void:
pass
fn twice[T < ?Copy](x: T) -> (T, T):
(x, x) # error: use-of-moved-value
fn show[T < ?Eq](x: T) -> void: # error: invalid-relaxed-bound
pass
fn dup[T](x: T) -> (T, T): (x, x)
fn demo(items: &mut List[i32], x: &mut i32) -> void:
writer := Writer { target: items }
pair := dup(writer) # error: unsatisfied-trait-bound
hs := [Holder { target: x }] # error: unsatisfied-trait-bound
photo := Photo { width: 2 }
keep(photo)
w := photo.width # error: use-of-moved-value
type Album(Photo)
fn shelve(album: Album) -> (Album, Album):
(album, album) # error: use-of-moved-valuestruct Photo:
width: u32
pixels: List[u8]
impl !Copy for Photo
trait Stored < ?Copy:
fn size(&self) -> u32
impl Stored for Photo:
fn size(&self) -> u32: self.width
fn handed[T < ?Copy & Stored](item: T) -> (T, u32):
size := item.size()
(item, size)Why. Copy is the default, as in Swift, because most generic code copies its values and a
Copybound on every declaration would be noise.?Copyis Rust's spelling for lifting a default bound, as?Sizedis. A trait'sSelfisCopyfor the same reason: only then may a default body copyself.
See also: Sealed Traits, Generic Bounds And Static Dispatch.
#Not Yet Checked
- ref.check.formatter
hd fmtformats a file that writes references. It keeps each reference token as written,&mutand*mutincluded, and a second run changes nothing.
fn slice(items: List[i32]) -> void:
part := &items[0..1] # error: type-mismatch