An Overview of the Rust Programming Language - 22rust4up
An Overview of the Rust Programming Language - 22rust4up
org
Jim Royer
CIS 352
CIS 352 Rust Overview 1/1 CIS 352 Rust Overview 2/1
CIS 352 Rust Overview 5/1 CIS 352 Rust Overview 6/1
Back to brag list from www.rust-lang.org, 1 Back to brag list from www.rust-lang.org, 2
zero-cost abstractions
efficient C bindings
minimal runtime
type inference These are performance goals borrowed from C++.
Rust’s type system is a cousin of ML’s and Haskell’s
Stroustrup on C++:
pattern matching
C++ implementations obey the zero-overhead principle:
as in ML and Haskell and Swift and . . .
What you don’t use, you don’t pay for.
trait-based generics And further:
in place of OO-classes, Rust uses a version of Haskell’s type-classes. What you do use, you couldn’t hand code any better.
This is much less bureaucratic that the standard OO framework.
‰ The prices Stroustrup is worried about paying are
the time and space used by running programs.
‰ . . . the time and effort binding wounds from repeated shooting
yourself in the foot — that is not Stroustrup’s concern.
‰ But Rust wants to avoid both sorts of prices.
CIS 352 Rust Overview 7/1 CIS 352 Rust Overview 8/1
Back to brag list from www.rust-lang.org, 3
guaranteed memory safety
threads without data races
These are safety guarantees. Why this is a big deal.
// ‘length‘ only needs ‘vector‘ temporarily, so it is borrowed. // ‘push‘ needs to modify ‘vector‘ so it is borrowed mutably.
fn length(vec_ref: &Vec<i32>) -> usize { fn push(vec ref: &mut Vec<i32>, x: i32) {
// vec_ref is auto-dereferenced when you call methods on it. vec ref.push(x);
vec_ref.len() }
} fn main() {
fn main() { let mut vector: Vec<i32> = vec![];
let vector = vec![]; let vector ref: &mut Vec<i32> = &mut vector;
length(&vector); push(vector ref, 4);
println!("{:?}", vector); // this is fine }
} Variables can be borrowed by mutable reference: &mut vec ref.
References, like bindings, are immutable by default. vec ref is a reference to a mutable Vec.
The type is &mut Vec<i32>, not &Vec<i32>.
The borrow is over after the reference goes out of scope (at the
Different from a reference which is variable.
end of length).
You can have exactly one mutable borrow at a time.
(usize =The pointer-sized unsigned integer type.)
Also you cannot dereference borrows (changes ownership).
Valid in C, C++,. . .
let y: &i32;
1 You can’t keep borrowing something after it stops existing. {
2 One object may have many immutable references to it (&T). let x = 5;
y = &x; // error: ‘x‘ does not live long enough
3 OR exactly one mutable reference (&mut T) (not both). }
println!("{}", *y);