0% found this document useful (0 votes)
5 views7 pages

An Overview of the Rust Programming Language - 22rust4up

The document provides an overview of the Rust programming language, highlighting its features such as ownership, borrowing, and memory safety. It includes sample code demonstrating recursive, iterative, and iterator versions of the factorial function. Additionally, it discusses Rust's approach to concurrency and the use of unsafe blocks for more control over memory management.

Uploaded by

smitpatelis231
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

An Overview of the Rust Programming Language - 22rust4up

The document provides an overview of the Rust programming language, highlighting its features such as ownership, borrowing, and memory safety. It includes sample code demonstrating recursive, iterative, and iterator versions of the factorial function. Additionally, it discusses Rust's approach to concurrency and the use of unsafe blocks for more control over memory management.

Uploaded by

smitpatelis231
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

www.rust-lang.

org

An Overview of the Rust


Programming Language

Jim Royer

CIS 352

April 29, 2019

CIS 352 Rust Overview 1/1 CIS 352 Rust Overview 2/1

References Sample code: Factorial, 1


The Rust Programming Language by S. Klabnik and C. Nichols, 2018.
https://doc.rust-lang.org/book/
A recursive version of factorial
Rust, N. Matsakis: http://www.slideshare.net/nikomatsakis/
guaranteeing-memory-safety-in-rust-39042975 fn fact_recursive(n: u64) -> u64 { u64 ≡ the type of unsigned
match n { 64bit integers
Rust: Unlocking Systems Programming, A. Turon, http://www.
0 => 1,
slideshare.net/InfoQ/rust-unlocking-systems-programming “n: u64” ≡ n is of type u64
_ => n * fact_recursive(n-1)
Rust’s ownership and move semantics, T. Ohzeki, http://www.slideshare. } “-> u64” ≡
net/saneyuki/rusts-ownership-and-move-semantics } the fn returns a u64-value
The Rust Programming Language, A. Crichton, a Google Tech Talk,
https://www.youtube.com/watch?v=d1uraoHM8Gg fn main () { match ≡ Haskell’s case
CIS 198: Rust Programming, University of Pennsylvania, Spring 2016, for i in 1..10 { (with pattern matching)
http://cis198-2016s.github.io println!("{}\t{}", 1..10 ≡ an iterator for the
i, fact_recursive(i)); numbers 1 through 9
Programming Rust, by Jim Blandy and Jason Orendorff, O’Reilly Media,
} (Yes, I mean 9.)
2017.
}
https://insights.stackoverflow.com/survey/2018/#technology-_
-most-loved-dreaded-and-wanted-languages
I shamelessly filch images and entire slides from these folks.
CIS 352 Rust Overview 3/1 CIS 352 Rust Overview 4/1
Sample code: Factorial, 2 Sample code: Factorial, 3

A iterative version of factorial


fn fact_iterative(n: u64) -> u64 {
let mut i = 1u64; A iterator version of factorial
let mut result = 1u64; fn fact_iterator(n: u64) -> u64 {
while i<=n {
“let mut i” ≡ declares a (1..n+1).fold(1, |p, m| p*m)
result *= i;
mutable variable i. }
i += 1; |p, m| p*m ≡ λp, m.(p ∗ m)
} “let j” ≡ declares a fn main () {
return result; immutable variable i. In fact, fact iterator ≡
for i in 1..10 {
} foldl (\p m->p*m) 1 [1..n]
1u64 ≡ u64-version of 1. println!("{}\t{}",
i, fact_iterator(i));
fn main () { The compiler figures out the }
for i in 1..10 { types of i and result. }
println!("{}\t{}",
i, fact_iterative(i));
}
}

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.

CIS 352 Rust Overview 9/1


What about using a GC? (like Haskell, Java, Go, . . . ) What about using a GC? (like Haskell, Java, Go, . . . )
Garbage collection: Garbage collection:
The programmer allocates vectors, strings, etc. The programmer allocates vectors, strings, etc.
The runtime system periodically sweeps through memory, looks The runtime system periodically sweeps through memory, looks
for unreferenced data and deallocates it. for unreferenced data and deallocates it.
8 Loss of control 8 Loss of control
8 Runtime overhead 8 Runtime overhead
8 Doesn’t help with other safety issues: iterator invalidation, data 8 Doesn’t help with other safety issues: iterator invalidation, data
races, etc. races, etc.
So, what is Rust’s solution? Ownership So, what is Rust’s solution? Ownership (affine linear typing)

CIS 352 Rust Overview 13 / 1 CIS 352 Rust Overview 13 / 1

Observation from C++-land Three Basic Patterns

Ownership fn foo(v: T) { ...}


Shared Borrow fn foo(v: &T) { ...}
Mutable Borrow fn foo(v: &mut T) { ...}

The next bunch of slides are from

∴ Outlaw doing both at once and appoint the compiler Sheriff.


CIS 198: Rust Programming, University of Pennsylvania, Spring 2016,
http://cis198-2016s.github.io/slides/01/

CIS 352 Rust Overview 14 / 1 CIS 352 Rust Overview 15 / 1


Ownership Move Semantics

A variable binding takes ownership of its data. [lifetimes]


A piece of data can only have one owner at a time. let v1 = vec![1, 2, 3];
When a binding goes out of scope, the bound data is released let v2 = v1; // Ownership of the Vec object moves to v2.
println!("", v1[2]); // error: use of moved value ‘v1‘
automatically.
For heap-allocated data, this means de-allocation. let v2 = v1;
Data must be guaranteed to outlive its references. We don’t want to copy the data, since that’s expensive.
The data cannot have multiple owners.
fn foo() { Solution: move the Vec’s ownership into v2, and declare v1 invalid.
// Creates a Vec object.
println!("{}", v1[2]);
// Gives ownership of the Vec object to v1.
let mut v1 = vec![1, 2, 3]; We know that v1 is no longer a valid variable binding, ∴ error!
v1.pop(); Rust can reason about this at compile time, ∴ compiler error.
v1.push(4); Moving ownership is a compile-time semantic.
// At the end of the scope, v1 goes out of scope. It doesn’t involve moving data during your program.
// v1 still owns the Vec object, so it can be cleaned up.
}

CIS 352 Rust Overview 16 / 1 CIS 352 Rust Overview 17 / 1

Ownership does not always have to be moved Borrowing

In place of transferring ownership, we can borrow data.


Rust would be a pain to write if we were forced to explicitly move A variable’s data can be borrowed by taking a reference to the
ownership back and forth. variable (i.e., aliasing); ownership doesn’t change.

fn vector_length(v: Vec<i32>) -> Vec<i32> {


When a reference goes out of scope, the borrow is over.
// Do whatever here, The original variable retains ownership throughout.
// then return ownership of ‘v‘ back to the caller
} let v = vec![1, 2, 3];
let v ref = &v; // v ref is a reference to v.
The more variables you had to hand back (think 5+), assert eq!(v[1], v ref[1]); // use v ref to access the data
the longer your return type would be! // in the vector v.
// BUT!
let v_new = v; // Error, cannot transfer ownership
// while references exist to it.

CIS 352 Rust Overview 18 / 1 CIS 352 Rust Overview 19 / 1


Borrowing Borrowing

// ‘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).

CIS 352 Rust Overview 20 / 1 CIS 352 Rust Overview 21 / 1

Borrowing Rules Borrowing Prevents: Use-after-free bugs

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);

This eliminates vast numbers of memory safety bugs at compile time!

CIS 352 Rust Overview 22 / 1 CIS 352 Rust Overview 23 / 1


The ownership rules also prevent other things Concurrency
Under the standard ownership rules:
You cannot implement doubly-linked lists (and circular structures
in general).
You cannot call C libraries.
... The ownership rules also turn out to be useful for implementing
safe concurrency (e.g., threads, interprocess communication, etc.)
Unsafe Rust
Standard currency primitives are not built in to Rust
unsafe { — they can be defined via ownership rules.
... Easy to use, safe (e.g., data-race free) concurrent programming is a
}
big deal.
Relaxes some of the checking rules.
Allows C libraries calls.
Allows access to raw pointers.
Allows you to implement language extensions, e.g.,
doubly-linked lists, garbage-collected pointers, etc.
CIS 352 Rust Overview 24 / 1 CIS 352 Rust Overview 25 / 1

Other goodies Nota Bena

Crate and cargo — a modern, simple to use project manager to


track dependencies, etc.
There isn’t a type-soundness proof for Rust yet.
Hygienic macros.
That is, the story Rust tells about what its types mean is nice
Growing collection of libraries (nowhere as near mature or — but can you prove that the story is correct?
complete as C, C++, Java, etc.) Problems:
Etc. Rust is a moving target.
See https://www.rust-lang.org for other resources. Rust includes unsafe-blocks.
If you want to learn Rust, don’t trust anything over three years
old. (Earlier versions were quite different.)

CIS 352 Rust Overview 26 / 1 CIS 352 Rust Overview 27 / 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy