Variables use let, functions use func, and both usually work without many type annotations. This chapter covers changing values, naming function arguments, passing functions around, and writing methods.
Bindings and assignment
Declare a local with let and optionally ascribe its type:
Every let binding can be assigned again; TalkTalk has no separate var keyword. Assignment also works with writable fields, tuple positions, and supported subscripts. Function signatures still control whether a function may change a value passed in from its caller: that is what mut means in the parameter and method examples below.
Destructuring uses patterns. A refutable pattern needs else:
Defining functions
A function may infer parameter and return types locally:
Annotations are recommended on public boundaries:
The final expression is returned implicitly. return without a value returns Void.
Argument labels
The declaration determines each call-site label:
A bare inferred parameter is positional. Adding a colon chooses a same-name label. A typed parameter is labeled unless _ suppresses it.
Parameter modes
Plain parameters are shared borrows by default. The complete set is:
borrow value: T- explicit shared borrowmut value: T- exclusive, writable accessconsume value: T- ownership supplied to the calleeconsume mut value: T- owned and locally writable
A mut argument must name a writable place and is marked at the call:
Ordinary and consuming arguments have no call-site marker. For shareable values, consume does not necessarily make the caller's name unusable: the compiler retains a snapshot when the caller has a later use.
Closures
Closures can use an explicit func form or a block form:
Block closures are especially convenient as call arguments. The $0, $1, and so on shorthand is available when the surrounding call supplies the closure's parameter types:
Functions can capture surrounding values. A final closure argument can move outside the parentheses:
Functions are values, so they can be stored in records and structs, passed as arguments, and returned. If a stored function uses an effect, such as asking for input, it uses the handler that is active when you call it. It does not permanently remember the handler from where it was created. See Effects for the full model.
Methods
Method signatures have an implicit self; do not declare it as a parameter. A plain method shares self, mut func may update it, consuming func takes it, and static func is called through the type: