Module 1 · Fundamentals
1.4Reading Rust's symbols: &, *, ', ::, ! and ?
A decoder for the punctuation that makes Rust look unfamiliar, with what each symbol means, its closest equivalent in your language, and when you'll use it.
On this page
- Concept map
- Borrowing and pointers: &, &mut, * and Box<T>
- Box<T>: one value on the heap
- Lifetimes and static: 'a, 'static and static
- Three different “static”s
- Paths, macros and errors: ::, ., ! and ?
- ? returns early on errors
- Patterns, ranges and the rest: .., _, |x| and #[...]
- Which one should I use?
- Under the hood
- Common pitfalls
- Try it yourself
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
& and &mut | No equivalent; objects are always shared | Roughly in and ref parameters | Borrow a value: read it (&) or change it (&mut) without owning it |
'a and 'static | No equivalent; the garbage collector keeps values alive | No equivalent; the garbage collector keeps values alive | Lifetimes: how long a borrow is valid. 'static means the whole program |
static | A module-level const or let | A member that belongs to a type, not an instance | A global item with one fixed address. Static methods are associated functions |
:: vs . | . for everything | . for everything | :: for paths and type-level items, . for methods and fields on a value |
? | ?. and ?? deal with null | ?., ?? and int? deal with null | Return early from the function on Err or None. Not related to ?. |
Box<T> | No equivalent | Not boxing: boxing silently copies a struct into an object | An owned value on the heap, freed when its owner goes out of scope |
Rust code can look like a wall of punctuation: &mut self, &'static str, String::from, println!, parse()?. Each symbol has one or two precise meanings, and several of them look like TypeScriptC# operators that mean something else. This lesson is a decoder. It explains each symbol only as deeply as you need to read code now, and links to the lesson that covers it properly. Come back to the table in Which one should I use? whenever a symbol stops you.
Borrowing and pointers: &, &mut, * and Box<T>
& borrows a value: it gives you access to it without taking ownership. &name is an expression that creates a reference, and &String is the type of that reference. It isn’t the address-of operator from C or C#‘s unsafe code: you can’t do arithmetic on it, it’s never null, and the compiler guarantees the value outlives it. (Between two values, a & b is still bitwise AND, as in TypeScriptC#.)
let name = String::from("Ada");
let borrowed = &name; // a shared borrow: no copy, `name` still owns the text
println!("{name} {borrowed} {}", borrowed.len());A plain & borrow is read-only, and you can have as many as you like at once. &mut is an exclusive borrow that can change the value. * dereferences: it gets to the value behind the reference, here to change it.
function increment(count: { value: number }): void {
count.value += 1;
}
const count = { value: 0 }; // a number can't be passed by reference: wrap it
increment(count);
increment(count);
console.log(count.value);var count = 0;
Increment(ref count);
Increment(ref count);
Console.WriteLine(count);
static void Increment(ref int count) => count += 1;fn increment(count: &mut i32) {
*count += 1; // `*`: change the i32 that `count` points at
}
fn main() {
let mut count = 0;
increment(&mut count); // lend `count`, mutably
increment(&mut count);
println!("{count}");
}Output
2
TypeScript has no references to variables at all: you wrap the number in an object and share the object. Rust lends the variable itself, and the compiler checks how it’s used.C#‘s ref is the closest idea, and in (or ref readonly) is close to &. The difference is what the compiler checks. While a &mut borrow exists, nothing else can read or write the value, so two parts of your program can never change the same data at the same time.
You’ll write & mostly in parameter types. A function says how it uses each argument:
fn print_name(name: &str) {
println!("{name}");
}
fn add_title(name: &mut String) {
name.insert_str(0, "Dr. ");
}
fn into_badge(name: String) -> String {
name + " (guest)"
}
fn main() {
let mut name = String::from("Ada");
print_name(&name); // lend it to read
add_title(&mut name); // lend it to change
let badge = into_badge(name); // give it away: `name` is moved
println!("{badge}");
}Notice that add_title calls a method on name without writing *. Method calls, field access and println! see through references automatically, so you write * mostly to assign through a &mut, or to get at the value itself: to copy it out or compare it with a plain number, as in *temp > 20. References covers the borrowing rules, and Choosing parameter types turns the three cases above into a decision table.
Box<T>: one value on the heap
Box<T> puts one value on the heap and owns it. When the box goes out of scope, the heap memory is freed. In TypeScript every object already lives on the heap, so the nearest thing is an object that holds a copy of the value. The name invites confusion with C# boxing, which happens silently when a value type such as int is converted to object: the runtime copies it into a new heap object.
let count = 42;
const boxed = { value: count }; // the nearest thing: an object holding a copy
count += 1;
console.log(`${count} ${boxed.value}`);int count = 42;
object boxed = count; // boxing: silently copies the int into a heap object
count += 1;
Console.WriteLine($"{count} {boxed}");let mut count = 42;
let boxed: Box<i32> = Box::new(count); // explicit: copies 42 into a heap allocation
count += 1;
println!("{count} {boxed}");Output
43 42
Both copy the value to the heap, and that’s where the similarity ends. Any number of variables can point at the object, and the garbage collector frees it some time after the last one lets go. A Rust box has exactly one owner and is freed the moment that owner goes out of scope. You read the value with *boxed.C# boxing is implicit, the result is typed only as object (or an interface), and the garbage collector frees it later. A Rust box is always written out, keeps its type (Box<i32>), has exactly one owner, and is freed the moment that owner goes out of scope. Getting the value back differs too: C# unboxes with a cast, (int)boxed, which copies the value out and throws if the type is wrong. In Rust, *boxed reads the value, and the type can’t be wrong. You rarely need one early on: Box<T> is for recursive types, very large values and trait objects (Box<dyn Trait>), covered in Modules 9 and 11.
Lifetimes and static: 'a, 'static and static
A word that starts with an apostrophe and has no closing quote, like 'a, is a lifetime: a name for how long a borrow is valid. ('a', with a closing quote, is a char. And a name with an apostrophe followed by a colon, such as 'outer: loop, is a loop label; Loops & conditional expressions covers those.) TypeScriptC# has nothing like it, because the garbage collector keeps any object alive while something points at it. Rust has no collector, so when a function returns a reference, the compiler needs to know which input it borrows from:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let winner = longest("Grace", "Ada");
println!("{winner}");
}Read <'a> as “for some lifetime a”, and the signature as “the result is valid for as long as both inputs are”. Most of the time you don’t write lifetimes at all: with one reference parameter, the compiler assumes the result borrows from it. This is called lifetime elision:
// The compiler reads this as: fn first_word<'a>(text: &'a str) -> &'a str
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
fn main() {
println!("{}", first_word("hello world"));
}Write lifetimes only when the compiler asks for them. Module 11 covers them in depth.
'static is the one lifetime with a built-in name: the borrow is valid for the whole run of the program. Every string literal is a &'static str, because its text is stored in the compiled program itself:
let greeting: &'static str = "hello"; // the text lives in the binary
println!("{greeting}");You’ll also see 'static as a bound, T: 'static, for example on the closure you pass to std::thread::spawn. That says something weaker: T holds no borrows that could expire, so it’s safe to keep for as long as you like. An owned String meets the bound, even though it’s freed normally when its owner goes out of scope. Module 11 covers the difference.
Three different “static”s
| You see | It means |
|---|---|
'static (with an apostrophe) | A lifetime: the borrowed data lives until the program ends. |
static NAME: T = ...; | A global item: one value at one fixed address for the whole program. |
static on a TypeScript classC#‘s static | A member that belongs to the classtype, not an instance. A static method is an associated function in Rust, such as String::from, defined in an impl block with no self parameter. No static keyword is involved. A static field becomes a const or a static item. |
The closest TypeScript has to a Rust static item is a module-level const or let: one value for the whole program, not tied to any class.
const APP_NAME = "binshelf"; // a module-level constant
function welcome(user: string): string {
return `Welcome to ${APP_NAME}, ${user}`;
}
console.log(welcome("Ada"));Console.WriteLine(App.Welcome("Ada"));
static class App
{
public static readonly string AppName = "binshelf";
public static string Welcome(string user) => $"Welcome to {AppName}, {user}";
}static APP_NAME: &str = "binshelf"; // a global item, not a type member
fn welcome(user: &str) -> String {
format!("Welcome to {APP_NAME}, {user}")
}
fn main() {
println!("{}", welcome("Ada"));
}Output
Welcome to binshelf, Ada
The type of APP_NAME is really &'static str: a static item can only hold 'static borrows, so Rust lets you leave the lifetime out. For most global constants, const is the better choice; Variables, mutability & shadowing compares the two.
Paths, macros and errors: ::, ., ! and ?
:: walks a path: through modules (std::mem::size_of), to an associated function or constant on a type (String::from, i32::MAX), or to an enum variant (Ordering::Less). . works on a value: methods (name.len()) and fields (point.x, pair.0). TypeScriptC# uses . for both.
A name followed directly by ! is a macro call: println!, format!, vec!. A macro expands into ordinary code at compile time. That’s how println! takes any number of arguments and checks its format string against them before the program runs.
const name = "Ada";
const upper = name.toUpperCase();
const biggest = Math.max(3, 7);
const names = ["Ada"];
names.push("Grace");
const line = `${upper} ${biggest} ${names.length}`;
console.log(line);var name = "Ada";
var upper = name.ToUpper();
var biggest = Math.Max(3, 7);
var names = new List<string> { "Ada" };
names.Add("Grace");
var line = $"{upper} {biggest} {names.Count}";
Console.WriteLine(line);let name = String::from("Ada"); // `::`: a function that belongs to String
let upper = name.to_uppercase(); // `.`: a method on the value `name`
let biggest = std::cmp::max(3, 7); // `::`: a path through modules
let mut names = vec!["Ada"]; // `!`: a macro that builds a Vec
names.push("Grace");
let line = format!("{upper} {biggest} {}", names.len());
println!("{line}");Output
ADA 7 2
One more use of :: you’ll meet early is the turbofish, ::<T>, which passes type arguments to a call: "42".parse::<i32>() means “parse this as an i32”. It’s what you’d write as method<number>() in TypeScriptMethod<int>() in C#, with :: added so the parser can tell < apart from less-than. The ! in a return type, -> !, is the never type from Functions, expressions & statements. And !x and != are logical not and not-equal, as in TypeScriptC#. (On an integer, !x flips every bit, like ~x in TypeScriptC#.)
? returns early on errors
A ? after a value of type Result or Option means: if this is an error (Err) or missing (None), return it from the current function right now; otherwise, unwrap the value and carry on. It’s the explicit version of an exception propagating up the call stack:
function parseInteger(text: string): number {
const value = Number(text);
if (!Number.isInteger(value)) {
throw new Error(`not an integer: ${text}`);
}
return value;
}
function addStrings(a: string, b: string): number {
return parseInteger(a) + parseInteger(b); // a throw skips the rest
}
const pairs: [string, string][] = [["2", "3"], ["2", "x"]];
for (const [a, b] of pairs) {
try {
console.log(addStrings(a, b));
} catch {
console.log("could not add");
}
}(string, string)[] pairs = [("2", "3"), ("2", "x")];
foreach (var (a, b) in pairs)
{
try
{
Console.WriteLine(AddStrings(a, b));
}
catch (FormatException)
{
Console.WriteLine("could not add");
}
}
static int AddStrings(string a, string b) => int.Parse(a) + int.Parse(b); // a throw skips the restuse std::num::ParseIntError;
fn add_strings(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x: i32 = a.parse()?; // on Err, return it from add_strings now
let y: i32 = b.parse()?;
Ok(x + y)
}
fn main() {
for (a, b) in [("2", "3"), ("2", "x")] {
match add_strings(a, b) {
Ok(sum) => println!("{sum}"),
Err(_) => println!("could not add"),
}
}
}Output
5 could not add
The match in main picks between the two outcomes; Exhaustive match & destructuring covers it. Result and ? get a full lesson in Module 6.
Common pitfall? is not ?.
TypeScript’sC#‘s user?.name turns a null into a null for that one expression and keeps going. Rust’s ? leaves the whole function, handing the Err or None to the caller. Rust has no ?. operator: you handle a missing value with Option methods or match, covered in Module 6.
Patterns, ranges and the rest: .., _, |x| and #[...]
.. has three jobs, all meaning “and the rest”:
- Ranges:
0..5is 0 to 4 (end excluded),1..=5is 1 to 5 (end included). You’ll use them inforloops and to slice:&scores[1..3]. - Rest patterns:
[first, .., last]matches the first and last elements and skips the middle. - Struct update:
Config { verbose: true, ..defaults }fills in every other field fromdefaults, like TypeScript’s{ ...defaults, verbose: true }C#‘sdefaults with { Verbose = true }. Note the two dots, and that they come last.
const scores = [90, 85, 77, 64];
const middle = scores.slice(1, 3);
const [first] = scores;
const last = scores.at(-1);
let sum = 0;
for (let i = 1; i <= 3; i++) {
sum += i;
}
console.log(`${first} ${last} ${middle.length} ${sum}`);int[] scores = [90, 85, 77, 64];
var middle = scores[1..3]; // copies two elements into a new array
var sum = 0;
for (var i = 1; i <= 3; i++)
{
sum += i;
}
if (scores is [var first, .., var last])
{
Console.WriteLine($"{first} {last} {middle.Length} {sum}");
}let scores = [90, 85, 77, 64];
let middle = &scores[1..3]; // borrows elements 1 and 2: no copy
let [first, .., last] = scores; // `..` skips the middle
let mut sum = 0;
for i in 1..=3 {
sum += i;
}
println!("{first} {last} {} {sum}", middle.len());Output
90 64 2 6
TypeScript has no range syntax: slice(1, 3) also excludes the end, and array destructuring can take the first elements but not the last.C# spells ranges (C# 8) and list patterns (C# 11) the same way: 1..3 excludes the end, and [var first, .., var last] skips the middle. Slices explains what &scores[1..3] points at.
_ means “I don’t need a name for this”. It ignores a value in a pattern, matches anything in a match, silences the unused-variable warning as a prefix, and asks the compiler to infer a type:
let (name, _) = ("Ada", 36); // ignore the second value
let _unused = 5; // a leading `_`: no unused-variable warning
let words: Vec<_> = "to be or not".split(' ').collect(); // `_`: infer the element type
let million = 1_000_000; // in a number, `_` is a separator
println!("{name} {} {million}", words.len());|x| expr is a closure, an anonymous function: the x => expr of TypeScriptC#. || with nothing between the bars is a closure with no parameters (and between two conditions it’s still logical or). Module 10 covers what closures capture.
const twice = (n: number) => n * 2;
const add = (a: number, b: number) => a + b;
console.log(`${twice(4)} ${add(2, 3)}`);var twice = (int n) => n * 2;
var add = (int a, int b) => a + b;
Console.WriteLine($"{twice(4)} {add(2, 3)}");let twice = |n: i32| n * 2;
let add = |a: i32, b: i32| a + b;
println!("{} {}", twice(4), add(2, 3));Output
8 5
#[...] is an attribute: an instruction to the compiler about the item below it. It looks like a TypeScript @decoratora C# [Attribute], but it’s handled entirely at compile time. TypeScript decorators are functions that run when the class is defined.C# attributes are mostly metadata that code reads through reflection at runtime. #[derive(...)] generates code, #[test] marks a test, and #[cfg(test)] compiles code only for tests. #![...], with a !, applies to the enclosing module or crate instead.
#[derive(Debug, Clone, PartialEq)] // generate {:?} printing, .clone() and ==
struct Point {
x: i32,
y: i32,
}
let a = Point { x: 3, y: 4 };
let b = a.clone();
println!("{a:?} {}", a == b);Which one should I use?
Here’s every symbol in one table. Keep it open while you read Rust code.
| Symbol | What it means | When you’ll see it | Closest in your language | Learn more |
|---|---|---|---|---|
&x, &T | A shared borrow: read without taking ownership. Many can exist at once. | Parameters (&str, &[T], &self), for x in &list. | None: objects are always shared.in or ref readonly, roughly. | References |
&mut x, &mut T | An exclusive borrow that can change the value. Only one at a time. | Functions that modify an argument, methods that take &mut self. | None.ref, plus an aliasing check C# doesn’t do. | References |
*x | Dereference: the value behind a reference or a Box. | *count += 1, copying a value out of a reference. (Between two numbers, it’s multiplication.) | None.*p in unsafe code only. | References |
Box<T> | One value on the heap with a single owner, freed when the owner goes out of scope. | Recursive types, Box<dyn Trait>, very large values. | None. An object holding a copy is the nearest thing.Not boxing. | Choosing parameter types, Module 11 |
'a | A lifetime: how long a borrow is valid. | Signatures that return a reference; structs that hold one. | None. | Module 11 |
'static | A lifetime that lasts the whole program. | &'static str (string literals), T: 'static bounds. | None. | Module 11 |
'x' | A char literal. Note the closing quote. | Any single character. | A one-letter string.'x'. | Primitive & compound types |
static NAME | A global item with one fixed address. | Global values that need one address; global counters. | A module-level const or let.A static field, but not on a type. | Variables, mutability & shadowing |
:: | A path: module, associated function or constant, enum variant. | String::from, std::mem::size_of, i32::MAX, Ordering::Less. | . on a type or namespace: Math.maxMath.Max. | Structs & impl blocks |
. | A method or field on a value. | name.len(), point.x, pair.0. | . | Structs & impl blocks |
::<T> | Turbofish: type arguments on a call. | "42".parse::<i32>(), .collect::<Vec<_>>(). | method<number>()Method<int>() | Module 9 |
name!(...) | A macro call, expanded at compile time. | println!, format!, vec!, panic!, assert_eq!. | None at the call site. | Module 13 |
-> ! | The never type: this never returns. | Functions that always panic or exit. | never.None. | Functions, expressions & statements |
? after a value | On Err or None, return it from the function; otherwise unwrap. | After calls that return Result or Option. | Not ?.. Closest: an exception propagating up. | Module 6 |
a..b, a..=b | A range, end excluded or included. | for i in 0..n, &s[1..3]. | None.1..3. | Loops & conditional expressions, Slices |
.. in a pattern or struct | “The rest”: remaining elements or fields. | [first, .., last], Point { x, .. }, ..defaults. | ...rest, { ...defaults }.List pattern .., with. | Exhaustive match & destructuring |
_ | Ignore this, or infer this type. | _ => in match, let _ = ..., Vec<_>, 1_000. | No discard (skip with a comma: [, second]). 1_000 is a separator here too.The _ discard. 1_000 is a separator here too. | Exhaustive match & destructuring |
|x| expr | A closure. | .map(|n| n * 2), callbacks. | x => expr | Module 10 |
#[...] | An attribute, processed at compile time. | #[derive(Debug)], #[test], #[cfg(test)]. | @decorator, which runs at runtime.[Attribute], mostly read through reflection at runtime. | Structs & impl blocks, Module 13 |
Rule of thumb: when you read &, think “borrow”; when you write a function, take &T to read an argument, &mut T to change it, and T to keep it. Don’t write lifetimes until the compiler asks for one. Use :: to reach into a type or module and . to call something on a value. Treat a trailing ! as “macro” and a trailing ? as “return early if this failed”. And when you see static, think “global item”, not a class member.And when you see Box<T> or static, forget what the words mean in C#.
Under the hood
A reference is just a pointer, a Box<T> is a pointer that owns its target, and neither carries any bookkeeping at runtime:
let mut count = 42;
let boxed = Box::new(count);
count += 1;
let borrowed = &count;
println!("{count} {boxed} {borrowed}");Lifetimes don’t exist at runtime at all. The compiler uses them to check that every reference points at a live value, then erases them, so 'a costs nothing. Here’s what it checks. Without lifetimes, longest doesn’t say whether its result borrows from a or b, and the compiler won’t guess:
fn longest(a: &str, b: &str) -> &str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
println!("{}", longest("Grace", "Ada"));
}Rust doesn't compile this: error E0106
error[E0106]: missing lifetime specifier
--> main.rs:1:33
|
1 | fn longest(a: &str, b: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
|
1 | fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
| ++++ ++ ++ ++The other symbols are just as cheap. :: and . are resolved at compile time. A macro is replaced by the code it expands to before type checking. And ? is shorthand for a match that returns the Err early (converting it with From if the function’s error type differs). References are never null, so Rust uses the null value to mean None: an Option<&i32> is the same size as a &i32.
use std::mem::size_of;
println!("&i32: {} bytes", size_of::<&i32>());
println!("Option<&i32>: {} bytes", size_of::<Option<&i32>>());
println!("Box<i32>: {} bytes", size_of::<Box<i32>>());
println!("&str: {} bytes", size_of::<&str>()); // pointer + length
println!("&[i32]: {} bytes", size_of::<&[i32]>()); // pointer + lengthOn a 64-bit machine that’s one 8-byte pointer, or two words when the reference also has to carry a length:
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
&i32 | ptr8 bytes · pointer | 8 bytes | |||||||||||||||
Option<&i32> | ptr (null = None)8 bytes · pointer | 8 bytes | |||||||||||||||
Box<i32> | ptr to heap8 bytes · pointer | 8 bytes | |||||||||||||||
&str | ptr8 bytes · pointer | len8 bytes | 16 bytes | ||||||||||||||
&[i32] | ptr8 bytes · pointer | len8 bytes | 16 bytes | ||||||||||||||
Each row is one type, and each cell is as wide as its size in bytes. &i32 is a single 8-byte pointer. Option<&i32> is the same 8-byte pointer, with the null value standing for None. Box<i32> is also a single 8-byte pointer, to its heap allocation. &str and &[i32] are 16 bytes: an 8-byte pointer to the first byte or element plus an 8-byte length, because the type alone doesn't say how many there are. The order of pointer and length inside them is how the compiler does it today, not a guarantee.
Common pitfalls
Common pitfallA reference can't outlive its value
In TypeScriptC#, an object lives as long as anything points at it. In Rust, a borrow must end before the value is dropped. This doesn’t compile, because count is freed at the inner } while r still points at it:
let r;
{
let count = 42;
r = &count;
}
println!("{r}");Rust doesn't compile this: error E0597
error[E0597]: `count` does not live long enough
--> main.rs:4:9
|
3 | let count = 42;
| ----- binding `count` declared here
4 | r = &count;
| ^^^^^^ borrowed value does not live long enough
5 | }
| - `count` dropped here while still borrowed
6 | println!("{r}");
| - borrow later used hereMove count to the outer scope, or store the value itself instead of a reference. References explains the rules.
Common pitfall? only works in a function that can return an error
? returns the error to the caller, so the function itself must return a Result (or an Option for None). A plain fn main() returns (), so this fails:
fn main() {
let count: i32 = "42".parse()?;
println!("{count}");
}Rust doesn't compile this: error E0277
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> main.rs:2:34
|
1 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
2 | let count: i32 = "42".parse()?;
| ^ cannot use the `?` operator in a function that returns `()`
|
help: consider adding return type
|
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 | let count: i32 = "42".parse()?;
3 | println!("{count}");
4 + Ok(())
|Return a Result from the function, or handle the error where it happens with match.
Common pitfallBox<T> doesn't turn a value into an object
In TypeScript, you wrap a number in an object to share or change it, as in the counter example above.In C#, boxing happens when a value type goes where an object or interface is expected. In Rust, generics, &T and &mut T work with any type directly, so you don’t need a box to pass, share, change or store a value. Boxing an i32 just adds a heap allocation. Reach for Box<T> only for recursive types, trait objects and very large values, and take &T in parameters: clippy flags functions that take a Box<T> they don’t need.
Common pitfallstatic doesn't make a type member
To give a type a function that doesn’t need an instance, like a TypeScript static create() methodC#‘s static string Create(), write an associated function in its impl block and call it with ::, as in String::from("Ada"). Rust’s static keyword declares a global item. Most of the time you want const for that instead, and changing a static needs unsafe or a thread-safe type such as an atomic.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Give add_bonus a mutable borrow of the score instead of an objecta ref parameter, and use ? instead of exceptions to stop at the first string that isn’t a number.
function parseScore(text: string): number {
const score = Number(text);
if (!Number.isInteger(score)) {
throw new Error(`not a number: ${text}`);
}
return score;
}
function addBonus(player: { score: number }, bonus: number): void {
player.score += bonus;
}
function finalScore(scoreText: string, bonusText: string): number {
const player = { score: parseScore(scoreText) };
addBonus(player, parseScore(bonusText));
return player.score;
}
const inputs: [string, string][] = [["10", "5"], ["10", "five"]];
for (const [scoreText, bonusText] of inputs) {
try {
console.log(finalScore(scoreText, bonusText));
} catch {
console.log("not a number");
}
}(string, string)[] inputs = [("10", "5"), ("10", "five")];
foreach (var (scoreText, bonusText) in inputs)
{
try
{
Console.WriteLine(FinalScore(scoreText, bonusText));
}
catch (FormatException)
{
Console.WriteLine("not a number");
}
}
static void AddBonus(ref int score, int bonus) => score += bonus;
static int FinalScore(string scoreText, string bonusText)
{
var score = int.Parse(scoreText);
AddBonus(ref score, int.Parse(bonusText));
return score;
}Expected output
15 not a number
Show a hint
add_bonus takes the score as &mut i32 and changes it with *score += bonus. final_score returns Result of i32 and ParseIntError, uses .parse()? for both strings, and lends the score with &mut score. In main, match on the result: Ok(score) prints it, Err(_) prints not a number.
Show a solution
use std::num::ParseIntError;
fn add_bonus(score: &mut i32, bonus: i32) {
*score += bonus;
}
fn final_score(score_text: &str, bonus_text: &str) -> Result<i32, ParseIntError> {
let mut score: i32 = score_text.parse()?;
let bonus: i32 = bonus_text.parse()?;
add_bonus(&mut score, bonus);
Ok(score)
}
fn main() {
for (score_text, bonus_text) in [("10", "5"), ("10", "five")] {
match final_score(score_text, bonus_text) {
Ok(score) => println!("{score}"),
Err(_) => println!("not a number"),
}
}
}&mut i32 lets add_bonus change the caller's score directly, and the * writes through it. Each ? hands a parse error straight back to main, just as the exception does in the starting code, but the Result in the signature makes that visible. String::from isn't needed: string literals are already &str.
Saved in this browser only.