Rust for a C programmer · Quick reference
First steps
The commands and terms used in your first Rust lessons.
Work inside the project directory
| Command | Purpose |
|---|---|
cargo check | Check compilation without generating the executable. Some errors appear only during a full build. |
cargo build | Build the project; the default development executable is under
target/debug/. |
cargo run | Build as needed, then run the program. |
Cargo.toml describes the package and its dependencies;
src/main.rs is the conventional source file for its default executable.
Cargo introduction ·
Building, running, and checking ·
Optional command details: cargo check.
Read the first program
| Syntax | Meaning here |
|---|---|
fn show(name: String) | Define a function taking an owned string by value. |
let name = …; | Introduce a variable; infer its type from the expression. |
String::from("report.txt") | Create an owned, growable UTF-8 string from a literal. |
println!("{name}"); | Format the value and print it with a newline. This use does not consume the string. |
let count: u32 = 7; | Declare an unsigned 32-bit integer explicitly. |
Functions · Types and inference · The String type · Printing values · Printing and ownership.
Print a computed value
A placeholder such as {text} can capture a variable name. A method call such as
text.len() goes in the macro's argument list, with a placeholder in the format string:
println!("{text}: {} bytes", text.len());
Or give the formatting argument a name:
println!("{text}: {len} bytes", len = text.len());
Here len = names the formatting argument; it does not declare a local variable.
{text.len()} is not a valid placeholder. Keeping a separate local len
variable is also a valid choice.
The Rust Book: variable and expression placeholders ·
Optional syntax details: named formatting arguments.
Lesson 03: format text and numbers practices alignment and returning a formatted String. Keep the formatting reference for syntax lookup.
Choose the argument’s ownership
| Parameter and call | Effect on the caller’s String |
|---|---|
name: Stringshow(name) | Move ownership into the function. |
name: &Stringshow(&name) | Borrow the owning String object; the caller keeps ownership. |
name: &strshow(&name) | Borrow its text; Rust converts the reference to a text view. The caller keeps ownership. |
With the &str parameter, show("inline.txt") also works:
string literals are already &str. Their full type is &'static str:
a pointer-and-length view of UTF-8 bytes stored in the program's binary and valid for the entire
program. There is no owning String object behind the literal. String::from("inline.txt")
creates an owned copy. The &String parameter requires an actual String object to borrow.
String is a standard-library type; str is a built-in UTF-8 text type whose size depends on its contents.
&str means a reference to that type, carrying a pointer and byte length.
&String instead refers to the owning String object, which tracks a buffer's pointer,
length, and capacity. Neither reference owns or frees the text.
Compare the three types.
References and borrowing · String slices as parameters · Practice in lesson 02.
Raw bytes and text
| Purpose | Bytes | UTF-8 text |
|---|---|---|
| Owned, growable buffer | Vec<u8> | String |
| Shared borrowed view | &[u8] | &str |
[u8; N] is a fixed array of N bytes; N is part of its type.
[u8] is a byte slice with no fixed length in its type;
&[u8] carries a pointer and a runtime length.
Byte arrays and slices permit any byte values. The distinct str type requires valid UTF-8.
let data: [u8; 4] = [0x00, 0x7f, 0x80, 0xff];
let view: &[u8] = &data;
let middle: &[u8] = &data[1..3]; // two bytes; end index excluded
The Rust Book: arrays · Other slices · Growable vectors · UTF-8 string types.
Ownership vocabulary
- Owner
- The variable or containing value responsible for a value’s cleanup. In lesson 01,
responsibility passes from
main’s local variable toshow’s parameter. - Move
- Transfer ownership. The previous location can no longer supply that value. “Move” describes what the program may do; the compiler may optimize away physical data movement.
- Drop
- Clean up a value. On normal scope exit, Rust drops the values still owned there.
Moving a value transfers cleanup responsibility to the new owner.
Dropping our
Stringreleases its heap buffer. Its last use alone does not trigger cleanup; in lesson 02 it remains owned untilmain’s scope ends. - Copy
- A type’s permission for implicit bitwise copying. Integers such as
u32have it;Stringdoes not. It is not a stack-versus-heap rule. - Clone
- An explicit operation, written
value.clone(). ForString, it creates another owned string with copied text. Cloning costs depend on the type.
Ownership · Copy · Clone · Automatic cleanup.
Cleanup may release resources such as locks as well as memory.
Use drop(name) to end ownership of this String and clean it up early.
Why cleanup timing matters ·
Dropping a value early.
Borrowing vocabulary
- Borrowing
- Accessing data while ownership remains elsewhere. Creating a reference borrows a value.
- Reference
- The value that provides borrowed access. In
let r = &name;,&nameborrowsname, andrholds a shared reference. Rust checks its validity; it does not permit changing this string through it. - Shared string slice (
&str) - A borrowed view of UTF-8 text with a byte length, covering all or part of a string. This is the usual parameter type for reading text, including an entire string.
References and borrowing · String slices.
Returning ownership or a borrow
Return String when handing a newly allocated text buffer to the caller;
ownership moves out of the function and the buffer remains allocated. Return &str
when lending text whose storage remains valid after the function returns. A reference does not
keep its allocation alive. The compiler rejects returning a borrow into a local String that
would be dropped, and rejects dropping an owner before a later use of its borrowed view.
Lifetime: the region of code for which a reference is valid. In
fn trimmed_name(name: &str) -> &str, Rust infers the relationship between
the input and returned borrow. The borrow can continue after the call; the text must remain valid.
Example and compiler checks ·
The Rust Book: dangling references.