ECS 36A Lecture Notes - Lecture 21: Substructural Type System, Compile Time

175 views3 pages
7 Dec 2018
School
Course
Professor
ECS 36A - Lecture 21 - Enumerations and Pattern Matching
fn max (x: &i32, y: &i32) →& i32 {
if x > y {
x
}else{
y
}
}
#Lifetimes only apply to reference types, values do not have lifetimes
- For every reference in the parameters, if it doesn’t have an explicit lifetime, then we
create a unique lifetime parameter for it → compiler creates 2:
fn max (x: &’a i32, y: &b i32) → &a i32{
- After applying the first rule, then we have lifetime parameters for all the input references:
if there is only one, then we use that one lifetime for all of the references: DOES NOT
apply here because there are two references in this example
Three obstacles of Rust:
1) Lifetime (Linear type system)
2) Generics -- concise error message
let x: i8 =1;
let y i8 = 2;
Let z i8 = max(x,y) #max expects i32 inputs not i8, does not compile
#Implicit castes can cause implicit errors, it’s disabled in Rust
let x: i8 =1:
let y i8 = 2;
let z i8 = max(x as i32, y as i32) as i8; #explicit casting, but it can still go out of range
Isize: machine dependent size -- fixed
Want to write a max function which can accept all types (i8, i32):
fn max<T>(x: T, y: T) → T{ #this is Generics, T is a type -- can define traits
if x > y {
x
}else{
y
}
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

Get OneClass Notes+

Unlimited access to class notes and textbook notes.

YearlyBest Value
75% OFF
$8 USD/m
Monthly
$30 USD/m
You will be charged $96 USD upfront and auto renewed at the end of each cycle. You may cancel anytime under Payment Settings. For more information, see our Terms and Privacy.
Payments are encrypted using 256-bit SSL. Powered by Stripe.