Skip to content

Commit

Permalink
Introduce a new chapter on label shorthand syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephTLyons authored and lpil committed Dec 22, 2024
1 parent 1495c29 commit 2b7dd35
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 16 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ build
erl_crash.dump
/public
/wasm-compiler
.DS_Store
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,6 @@ pub fn main() {

// Using the labels in a different order
io.debug(calculate(1, multiply: 3, add: 2))

// You may have some local variables declared
let multiply = 3
let add = 2

// You can specify the variables by name when calling the function
io.debug(calculate(1, add: add, multiply: multiply))

// Or use shorthand syntax, if the variable names match the names of the
// labelled arguments
io.debug(calculate(1, add:, multiply:))
}

fn calculate(value: Int, add addend: Int, multiply multiplier: Int) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,3 @@
Labels are optional when calling a function, it is up to the programmer to
decide what is clearest in their code.
</p>
<p>
Additionally, when local variables have the same name as the labelled
argument, the variable name can be omitted when calling the function. This is
known as shorthand syntax for labels.
</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
pub fn main() {
let quantity = 5.0
let unit_price = 10.0
let discount = 0.2

// Explicitly providing local variable names when calling the function.
calculate_total_cost(
quantity: quantity,
unit_price: unit_price,
discount: discount,
)

// However, since our local variable names are identical to the argument
// labels, we can omit the variable names entirely and use shorthand label
// syntax.
calculate_total_cost(quantity:, unit_price:, discount:)
}

fn calculate_total_cost(
quantity quantity: Float,
unit_price price: Float,
discount discount: Float,
) -> Float {
let subtotal = quantity *. price
let discount = subtotal *. discount

subtotal -. discount
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<p>
When local variables have the same names as a function's labelled arguments,
the variable names can be omitted when calling the function. This is known as
shorthand syntax for labels.
</p>

0 comments on commit 2b7dd35

Please sign in to comment.