Lecture 3: Types and Systems Programming
Lecture 3 discusses some of the concepts around types and type systems,
and tries to highlight the benefits of moving from a weakly-typed
language, such as C, to a more strongly-typed, safer, systems
programming language. It begins to introduce the Rust programming
language, as an example of such a safer systems programming language.
Part 1: Types and Systems Programming
The first part of this lecture discusses the idea of types in programming
languages. It review what is a type and a type system, and discusses
the concepts of static vs. dynamic typing, strong vs. weak types, and
safe vs. unsafe programming languages. It highlights the benefits of
strongly typed safe languages for systems programming.
00:00:00.466
In this lecture, I want to move
00:00:02.600
on from the general discussion of the
00:00:05.200
problems with systems programming, and talk about
00:00:07.800
types and systems programming in more specific terms.
00:00:11.000
In particular, I want to talk about
00:00:13.300
strongly typed languages, talk a bit about
00:00:15.700
what is a strongly typed language,
00:00:18.133
why strong typing is desirable,
00:00:20.133
and how we can make use of types for systems programming.
00:00:23.800
And I want to move on and start to
00:00:25.600
introduce the Rust programming language,
00:00:27.666
talking about the basic operations and types
00:00:29.600
that are feasible in that language,
00:00:31.400
the way it does pattern matching and
00:00:34.400
memory management, and finally talk a bit
00:00:37.666
about why Rust is interesting
00:00:40.266
as a systems programming language.
00:00:43.300
To begin, I want to talk about strongly typed languages.
00:00:46.700
I want to talk about what is strongly typed language,
00:00:49.666
why it's desirable,
00:00:50.966
and how types can be used for systems programming.
00:00:55.500
So first of all, what is a type?
00:00:58.266
Well, a type in programming languages is
00:01:01.000
something which describes what an item of
00:01:03.300
data represents.
00:01:05.233
It tells us whether a particular variable
00:01:07.833
can hold an integer, a floating point
00:01:10.433
value, a file, a sequence number,
00:01:12.666
a username, or whatever it happens to
00:01:14.700
be. It says conceptually what is the
00:01:17.366
data which is represented by a variable,
00:01:20.000
and how is that data represented?
00:01:22.833
Types are very familiar in programming.
00:01:25.233
For example, if we look at the
00:01:26.433
code on the right hand side of
00:01:28.400
the screen, which is C code,
00:01:30.166
we see a number of variable declarations.
00:01:32.300
We can specify the types of the variable.
00:01:34.666
We specify that x holds an integer,
00:01:37.033
for example; that y holds a double
00:01:39.200
precision floating point value; and that the
00:01:41.366
variable hello is a pointer to a
00:01:43.533
character, in this case a pointer to
00:01:45.733
the first character of the string “Hello, world”.
00:01:48.100
We also see that it’s possible to
00:01:50.066
define new types. For example, the definition
00:01:53.300
of the struct, struct sockaddr_in, on the slide
00:01:56.600
defines a compound type holding five fields:
00:02:00.033
length, family, port, addr, and some padding.
00:02:03.266
Each of which has its own type,
00:02:05.333
and the type of one of these
00:02:07.533
is, in turn, a compound type, struct in_addr.
00:02:11.566
This lets us build up reasonably complex
00:02:14.233
types, to represent the different types of
00:02:16.200
data that we’ll work with in our program.
00:02:19.700
So given this definition of a type,
00:02:22.233
what is a type system?
00:02:23.733
Well, a type system is a set of
00:02:26.366
rules that constrains how the types can be used.
00:02:29.300
The type system specifies what operations can
00:02:32.066
be performed on particular types of data.
00:02:34.900
What operations can be performed with those
00:02:37.000
types of data, and how the different
00:02:40.033
types of data compose with other types
00:02:42.166
of data to form compound data types,
00:02:45.033
or types specifying different alternatives.
00:02:49.266
A type system specifies what the program
00:02:52.633
can do. It specifies the legal behaviour
00:02:55.533
for objects of those particular types.
00:02:58.066
Equally, it proves that the program can't
00:03:01.033
do certain things. It proves that the
00:03:04.000
program can't perform certain illegal behaviours.
00:03:06.666
This doesn't guarantee that the program is
00:03:09.400
correct, of course, but it does guarantee
00:03:12.133
that some types of incorrect behaviour don't
00:03:14.900
occur in a well-typed program.
00:03:16.966
Type systems eliminate certain classes of bugs,
00:03:19.700
hopefully without adding too much
00:03:21.466
complexity to the language.
00:03:23.900
Some of the bugs the
00:03:25.600
type system helps us prevent are straightforward.
00:03:28.500
It prevents us adding apples to oranges
00:03:31.400
and getting a meaningless answer, for example.
00:03:34.366
Or it guarantees that we can't access
00:03:36.900
the 11th element of the collection,
00:03:38.566
which only holds 10 elements. Some type
00:03:41.600
systems can help protect against more subtle bugs, though.
00:03:44.466
Modern type systems, for example, can help
00:03:47.400
make sure that race conditions don't occur
00:03:49.833
in multi threaded code. Or they can
00:03:52.233
check various invariants of the program behaviour,
00:03:54.666
and check that particular features of the design are upheld.
00:03:58.233
The goal of designing a type system
00:04:00.633
is to balance complexity, through the complexity
00:04:03.000
and the features of the type system,
00:04:05.400
with the ability to catch bugs.
00:04:07.566
A badly designed type system adds complexity
00:04:10.500
and syntactic overhead to the language,
00:04:12.500
but doesn't really catch any problems.
00:04:15.566
Some would suggest that the type system
00:04:18.533
in languages like Java is in this category.
00:04:21.733
Ideally what we want, though, is a
00:04:24.400
language where the type system is sophisticated
00:04:26.800
enough to catch real problems with the
00:04:29.166
code, yet low enough overhead that people
00:04:31.100
are willing to use it.
00:04:33.400
Types are a fundamental feature of a
00:04:35.600
program. We’re used to thinking of types
00:04:37.833
as a compile time feature because the
00:04:40.033
compiler complains when we get them wrong.
00:04:42.366
But types exist at runtime too,
00:04:44.700
and certain types of type checking also happen at runtime.
00:04:48.566
For example, array bounds checks are very much a property of
00:04:51.233
an array type, but are typically checked at runtime,
00:04:54.100
rather than compile time.
00:04:57.866
Different languages have different type systems.
00:05:01.466
Some languages are strongly typed, and provide
00:05:04.266
no flexibility, no escape from the type rules.
00:05:07.166
In others, the type checking is much
00:05:09.966
weaker, and it's possible to subvert the
00:05:12.366
rules or to cast between different types of data.
00:05:15.533
Some languages apply types statically, and when
00:05:17.833
a variable is assigned a particular type,
00:05:20.133
its type can never change and it
00:05:22.433
can only hold variables of, hold values of, that type.
00:05:25.800
Other languages are more dynamic, and allow
00:05:27.933
the types that variables can hold to
00:05:29.866
change at different points in the program.
00:05:34.333
There are different trade offs here.
00:05:36.033
There's no right or wrong answer.
00:05:37.900
And when we're thinking about type systems,
00:05:39.833
we need to think about, to what
00:05:42.066
extent the typing rules are strictly enforced,
00:05:44.166
and to what extent objects can change
00:05:46.633
their types as the program’s execution proceeds.
00:05:52.033
In a language with static types,
00:05:53.933
the type of a variable is fixed.
00:05:56.166
In the example at the bottom of
00:05:58.400
the slide, for example,
00:05:59.600
we have a Rust program which declares
00:06:02.133
the variable x to hold an integer
00:06:04.500
type and then tries to add the
00:06:06.866
floating point number 4.2 to it.
00:06:09.000
And since Rust is a statically typed
00:06:11.466
language, this fails and the compiler complains
00:06:13.966
that you can't add a floating point
00:06:16.433
number to a value which is holding
00:06:18.900
an integer type. The types don’t match.
00:06:21.466
What's interesting in this example, though,
00:06:23.500
is that we never specified that the
00:06:25.833
variable x holds an integer type
00:06:27.933
Some statically typed languages require that the
00:06:30.800
types of variables are explicitly declared.
00:06:33.233
C and C++ and Java fall into
00:06:36.100
this category, for example. Others, like Rust,
00:06:38.966
and like the example we see on
00:06:41.833
the slide, can infer types from the context.
00:06:44.833
However, just because the language can infer
00:06:47.433
the type of variable doesn't mean that
00:06:49.666
the type is dynamic.
00:06:51.033
With Rust, once the type of variable
00:06:53.600
x has been inferred to be an
00:06:55.433
integer we can't add a floating point
00:06:57.766
value to it, even though we never
00:07:00.666
explicitly said that x can hold integers.
00:07:02.600
The type is still static, it just
00:07:04.733
saves us the typing of specifying what it is.
00:07:09.766
In other languages, the types are much more dynamic.
00:07:13.200
The example show some Python code.
00:07:15.033
And again, we set a variable x
00:07:17.200
the hold the value six. We inspect
00:07:18.866
its type, and we see that its
00:07:21.233
type is an integer. And again,
00:07:23.333
Python has inferred the type in much
00:07:25.533
the same way that Rust did in the previous slide.
00:07:28.700
However in this case, when we add
00:07:30.800
the value 4.2 to it, which is
00:07:32.866
a floating point value, it succeeds.
00:07:34.900
And if we look at the type,
00:07:36.733
we inspect the type of x,
00:07:38.533
we see that its type has changed
00:07:40.600
to that of a floating point number
00:07:42.766
In Python types of dynamic, and it's
00:07:45.633
safe to convert an integer to a
00:07:48.466
floating point value, it doesn't lose any
00:07:51.333
information, so when we ask the interpreter
00:07:53.466
to do so, the conversion succeeds
00:07:55.066
and the type of the variable changes.
00:07:59.566
Which is better, a dynamically typed language
00:08:03.133
or statically typed language?
00:08:05.266
Well, it very much depends what you're
00:08:07.200
doing, and there are different trade offs.
00:08:09.200
Dynamically typed languages tend to perhaps be
00:08:12.200
lower performance, but they offer more flexibility.
00:08:15.266
A dynamically typed language has to store
00:08:17.333
the type of a variable as well
00:08:19.400
as its value at runtime. And this
00:08:21.466
tends to take up additional memory.
00:08:23.333
It also has to check that the
00:08:25.366
variables are of the correct type before
00:08:27.366
it performs the various operations, and it
00:08:29.400
has to perform those checks at runtime.
00:08:31.400
Again, because the types can change over time.
00:08:33.600
And similarly, it can make fewer optimisations
00:08:36.566
based on the types of the variable,
00:08:38.566
again because the types of can change.
00:08:42.166
Systems languages tend to have static types,
00:08:44.733
and they tend to be compiled ahead
00:08:47.266
of time, because they’re performance sensitive.
00:08:49.533
If the types of fixed, and if
00:08:51.500
that the compiler can look at code
00:08:53.466
and make optimisation decisions based on the code,
00:08:55.733
and can do so ahead of time,
00:08:57.766
without worrying about performing those
00:08:59.833
optimisations quickly,
00:09:00.966
it can generally achieve better performance.
00:09:03.333
Systems programming languages tend to trade-off performance
00:09:07.633
for flexibility, and have very static type systems.
00:09:12.100
In a language with strong types,
00:09:14.366
every operation must conform to the type system.
00:09:17.500
A strongly typed language makes sure that
00:09:19.866
operations which can't be proven to be
00:09:21.866
correct, that can't be proven to conform
00:09:24.166
to the typing rules, are not permitted.
00:09:27.466
More weakly type languages provide ways of
00:09:30.566
circumventing the type checker.
00:09:32.466
For example, a lot of languages allow
00:09:35.366
safe conversions, safe and automatic conversions,
00:09:37.866
between certain types. For example, a lot
00:09:40.133
of languages allow conversions between floating point
00:09:43.700
and double precision types, to extend the
00:09:46.600
precision of a type, or from an
00:09:49.533
integer to a long integer
00:09:52.200
And in all these cases the conversion is safe.
00:09:56.133
In other cases, the language can allow
00:09:58.566
more open-ended casts. The code fragments at
00:10:00.966
the bottom of the slide shows a
00:10:03.066
common idiom in C.
00:10:04.900
The variable, buffer, holds an unstructured sequence
00:10:07.800
of characters, and the recv() call reads
00:10:09.833
data into that buffer.
00:10:12.466
Once the read has successfully retrieved that
00:10:15.300
data, it’s cast to a different type
00:10:18.100
representing the expected contents of the buffer.
00:10:21.033
This is very unsafe behaviour. The programmer
00:10:23.666
is essentially telling the compiler “Trust me,
00:10:26.300
I know what I’m doing”. Trust that
00:10:28.933
this sequence of bytes is actually,
00:10:31.200
in this example, an RTP packet.
00:10:33.566
If the programmer is correct, and the
00:10:36.233
sequence of bytes really is an RTP
00:10:38.366
packet, this is safe and high performance.
00:10:41.200
If the programmer is not correct,
00:10:44.066
the data doesn't match its type,
00:10:46.500
then the behaviour is undefined.
00:10:49.766
A weakly type language provides these sort
00:10:52.566
of escape hatches. Ways of circumventing the
00:10:54.633
type system. Ways of telling the compiler
00:10:57.066
“Trust me, I know what I'm doing”.
00:10:59.666
This can provide a lot of power.
00:11:01.600
It's also very risky because if the
00:11:04.200
programmer gets it wrong, the program crashes unpredictably
00:11:10.233
When thinking about strong and weak types,
00:11:12.966
it’s essentially important to them in the
00:11:15.700
context of safe and unsafe languages.
00:11:18.166
A safe language, whether the typing is
00:11:20.700
static or dynamic, knows the types of
00:11:23.266
all the variables, and only allows legal
00:11:25.833
operations on those values at any time.
00:11:28.500
An unsafe language, on the other hand,
00:11:30.833
allows the types to be circumvented.
00:11:32.800
It allows the programmer to specify to
00:11:35.133
the compiler “Trust me, I know what I'm doing”.
00:11:38.233
It lets the programmer perform operations which
00:11:40.633
they believe to be correct, even though
00:11:43.033
the type system can't prove them to be so.
00:11:46.200
It pushes the burden of checking for
00:11:48.566
correctness onto the programmer, rather than allowing
00:11:51.000
the type system to help.
00:11:54.133
Unsafe languages provide a lot of flexibility.
00:11:56.633
They allow you to do things which
00:11:59.133
are not possible in safe languages.
00:12:01.366
They’re also much riskier. It's much easier
00:12:05.066
to mess up in an unsafe language,
00:12:07.766
and to have the program crash.
00:12:11.600
And this is why strong typing is
00:12:14.033
desirable, I think. Results for a program
00:12:16.433
that only use strong types are always
00:12:18.866
well defined. The language is always safe.
00:12:21.366
The results are always consistent with the
00:12:23.700
rules of the language.
00:12:25.166
A strongly typed program only ever performs
00:12:28.200
operations that are legal. It can never
00:12:30.233
perform undefined behaviour.
00:12:32.633
Strong typing helps us model the problem
00:12:35.233
space. It helps us check our designs
00:12:37.833
and the resulting code for consistency.
00:12:40.066
It helps eliminate certain classes of bugs.
00:12:42.766
That is, the type system can't prove
00:12:45.366
that the program is correct, but it
00:12:47.966
can prove that certain behaviours don't happen
00:12:50.600
because they're not legal for those types.
00:12:53.300
Weakly typed systems, on the other hand,
00:12:55.866
can't make such guarantees, because the programmer
00:12:58.766
always has the option of circumventing the type system.
00:13:03.566
We've all seen this message, segmentation fault
00:13:07.233
(core dumped), when writing C programs.
00:13:10.500
I'd argue, though,
00:13:11.866
that segmentation faults should never happen.
00:13:14.566
The compiler and the runtime should be
00:13:17.266
able to enforce the typing rules,
00:13:19.566
and make sure that if the program
00:13:22.266
violates them, it's terminated cleanly.
00:13:24.266
A segmentation fault happens when the program
00:13:27.233
is not terminated cleanly, and the program
00:13:29.766
perform some behaviour which is illegal,
00:13:31.733
accesses memory which it doesn't own,
00:13:33.700
and the operating system kills it.
00:13:37.966
That's a useful safety measure. It's important
00:13:40.866
that the operating system can stop wayward programs.
00:13:44.200
Unfortunately, it's not a very precise safety measure.
00:13:47.633
There are lots of behaviours which access
00:13:49.966
memory outside the bounds of an object,
00:13:52.300
but which don't go outside the bounds
00:13:54.666
of memory allocated by the operating system.
00:13:57.100
These give undefined behaviour. They silently corrupt
00:14:00.333
and modify other parts of the program’s
00:14:03.600
state. It’s these types of types of misbehaviour
00:14:06.666
that tend to lead to security
00:14:08.500
vulnerabilities, as a result of undefined behaviour
00:14:12.066
due to weak type systems.
00:14:15.766
The C programming language is especially bad
00:14:19.066
for this. The C standard documents 193
00:14:22.366
different kinds of undefined behaviour in the language.
00:14:26.233
And I think what's more worrying is
00:14:28.633
that any of these undefined behaviours can
00:14:31.033
lead to entirely unpredictable results.
00:14:32.866
If the program hits undefined behaviour,
00:14:35.300
the standard says anything can happen.
00:14:37.733
It doesn't make any guarantees. That's really
00:14:40.566
worrying if we're trying to write secure,
00:14:43.400
correct, and trustworthy code.
00:14:45.133
The link on the slide, to the
00:14:48.466
blog post, points to some discussion of
00:14:51.433
this. And it's really quite alarming the
00:14:53.633
sorts of behaviours that C programs can perform.
00:14:59.366
As we've seen, C is a weakly typed language,
00:15:02.466
yet it's widely used for systems programming.
00:15:05.700
Why is this, why do we use
00:15:08.333
a language which provides so few guarantees?
00:15:10.666
And can we write systems programs in
00:15:13.033
languages which are strongly typed? And what
00:15:15.266
are the difficulties in doing so?
00:15:18.500
Well, I think, the question is why
00:15:20.933
C is weakly typed is a historical accident.
00:15:24.966
Partly is because the original designers of
00:15:28.200
C were not type theorists.
00:15:30.166
They were operating systems designers,
00:15:32.133
rather than programming language
00:15:34.300
designers, programming language theorists.
00:15:36.533
In part, it's because of the machines
00:15:38.866
and which C was developed didn't have
00:15:41.200
the resources to perform complex type checks.
00:15:43.666
Even if the people designing the language
00:15:46.100
had been experts in programming language theory,
00:15:48.566
and even if we’d had sophisticated type
00:15:51.000
systems and the ability to perform such
00:15:53.466
checks, the machines they were running the
00:15:55.900
code on, didn't have the resources to do that.
00:15:59.166
In part because type theory wasn't particularly
00:16:02.000
well advanced in the early 1970s,
00:16:03.833
when C was being designed.
00:16:05.500
We didn't know how to perform
00:16:07.266
the various checks that are possible today.
00:16:11.900
Is strongly typed systems programming feasible?
00:16:15.266
Well, yes, I think it is.
00:16:17.333
In fact, there's been many examples of operating
00:16:19.566
systems which are written in strongly typed languages.
00:16:22.966
The original version of the Mac operating
00:16:25.566
system, for example, was written in Pascal.
00:16:28.266
There was a research project in the 80s
00:16:31.000
known as project Oberon, which used a
00:16:33.733
language called Oberon, a descendant of Pascal
00:16:36.500
to write operating systems.
00:16:38.166
And the US Department of Defence developed
00:16:41.033
the Ada programming language for aerospace,
00:16:43.500
military applications, and air traffic control,
00:16:45.733
and that's very much a strongly typed
00:16:48.333
language designed for systems programming.
00:16:51.000
The code fragment on the right is
00:16:53.233
a sample of Ada code. And we
00:16:55.466
see that it very precisely specifies the
00:16:57.700
ranges of the various numeric types.
00:16:59.733
It specifies that the order in which
00:17:02.533
fields are packed into the various control
00:17:05.233
registers. It even specifies the byte order
00:17:08.166
of the types. In some ways it
00:17:10.600
provides even more low level control than
00:17:13.300
C does, although perhaps in a much more verbose way.
00:17:17.800
Over the years the popularity of C
00:17:20.400
and Unix has kind of led to
00:17:22.633
a belief that operating systems require unsafe
00:17:24.866
weakly type code.
00:17:26.866
That may be true at the very lowest levels;
00:17:30.300
programming interrupt registers, programming particular
00:17:32.866
hardware registers, but most systems code,
00:17:35.666
including most device drivers, can pretty much
00:17:38.466
be written in strongly typed safe languages,
00:17:41.500
with only tiny fragments of unsafe code.
00:17:44.600
The Rust programming language is a modern
00:17:47.466
attempt to try and provide a type
00:17:50.300
safe language which is suitable for systems programming.
00:17:53.433
What I hope to show in this
00:17:55.666
course, is that this is very much
00:17:57.733
achievable, and we can use safe languages
00:17:59.833
to write systems programs.
00:18:02.866
What I've done in this lecture.
00:18:05.000
I've spoken a little bit about what
00:18:07.533
is a strongly typed language, and the
00:18:10.033
differences between strong and weak typing,
00:18:12.200
and static and dynamic typing, and the
00:18:14.733
differences between safe and unsafe languages.
00:18:16.966
I’ve hopefully explained why strong typing is
00:18:19.633
desirable, and talked a little bit about
00:18:22.300
types for systems programming.
00:18:23.900
In the remainder of this lecture,
00:18:25.800
I'll start by introducing the Rust programming
00:18:28.000
language as an example of a statically
00:18:30.200
typed, strongly typed language, which I believe
00:18:32.400
is suitable for systems programs.
Part 2: Introducing Rust (1/4)
The second part of the lecture introduces the Rust programming language,
as an example of a strongly typed systems programming language. It
reviews the basic features and types of Rust.
00:00:00.533
In this second part, I want to
00:00:02.766
Introduce the Rust programming language,
00:00:04.866
with a focus on basic types and operations.
00:00:09.000
The Rust programming language is a modern
00:00:11.233
systems programming language.
00:00:13.466
It was initially developed by Graydon Hoare
00:00:15.666
as a side project, starting in 2006,
00:00:18.766
and development was sponsored by Mozilla for
00:00:21.033
over ten years starting in 2009.
00:00:24.366
The 1.0 release of the language was
00:00:26.733
made in 2015. And in December 2018,
00:00:30.466
a cleaned-up but backwards compatible version,
00:00:33.000
the Rust 2018 Edition, was released.
00:00:36.466
Since then, Rust has released new versions
00:00:39.066
every six weeks, maintaining a strong policy
00:00:41.533
of ensuring backwards compatibility
00:00:43.766
while adding new features.
00:00:48.000
The Rust version of the “Hello,
00:00:49.800
world!” program is shown on the slide.
00:00:52.466
As with many other languages, execution starts
00:00:55.233
with the main function.
00:00:57.366
Functions are defined with the fn keyword,
00:01:00.766
followed by the function name, its arguments
00:01:03.466
within parenthesis, and any return type.
00:01:06.566
The main() function in the example takes
00:01:09.000
no arguments and returns nothing.
00:01:12.000
The body of the function follows,
00:01:13.600
enclosed in braces.
00:01:16.100
In this case, the body comprises a
00:01:18.333
macro, println!(), that’s expanded at compile time.
00:01:22.800
Macro invocations in Rust always end with
00:01:25.400
an exclamation point, to distinguish them from
00:01:27.633
function calls. Macros in Rust are a
00:01:30.533
more sophisticated, and type safe, version of
00:01:33.366
the #define feature in C.
00:01:38.133
This slide shows a slightly more sophisticated example.
00:01:42.200
The first line is a use statement,
00:01:44.566
that imports a library module. In this
00:01:47.066
case, the module env, that provides command
00:01:49.366
line argument parsing, is imported from the
00:01:51.600
standard library.
00:01:53.666
A use statement brings the public functions,
00:01:56.166
types, and other definitions of the imported
00:01:58.433
module into scope. Those functions can then
00:02:01.800
be referenced by name, relative to the
00:02:03.733
imported path, much like imports in Python.
00:02:07.866
For examples, this code call the env::args() function.
00:02:12.966
The main() function in this example shows
00:02:15.733
a for loop in operation. The env::args()
00:02:18.700
function returns an iterator that returns the
00:02:21.166
command line arguments one-by-one, and the for
00:02:23.866
loop consumes the values generated by that
00:02:25.866
iterator, executing the body for each in turn.
00:02:30.700
The println!() macro takes format strings to
00:02:33.566
specify how values are printed. This works
00:02:36.333
a lot like the format string in
00:02:38.100
a C printf() statement, except that the
00:02:40.233
format specifiers are surrounded by braces rather
00:02:42.533
than preceded by a % sign.
00:02:45.900
As we see from the bottom of
00:02:47.633
the slide, this program prints its command line arguments
00:02:53.000
This third example is more sophisticated still.
00:02:57.266
Looking at the main() function, we see
00:02:59.933
that variables are defined in let bindings,
00:03:02.366
such as “let m = 12”.
00:03:05.400
This defines a new variable, m,
00:03:07.800
and binds the value to that variable.
00:03:11.000
The type of the variable is inferred
00:03:12.833
from the context. If the compiler can’t
00:03:16.100
infer the type, it can be specified
00:03:18.366
by following the variable name with a
00:03:20.000
colon, then the type name, before the
00:03:22.133
assignment of the value.
00:03:24.566
By default variable bindings are immutable.
00:03:28.033
That is, the value of the variables
00:03:30.066
m, n, and r in this function
00:03:32.900
cannot be changed after they have been bound.
00:03:36.500
To make a mutable binding, that is
00:03:38.933
a variable whose value can change,
00:03:41.166
add the “mut” qualifier following the let
00:03:43.333
statement. For example, one could write “let
00:03:46.833
mut m = 12” to make m a mutable variable.
00:03:52.200
Finally in main(), we see a call
00:03:54.266
to the gcd() function, to calculate the
00:03:56.800
greatest common divisor of m and n.
00:04:00.666
The gcd() function is defined first in
00:04:03.733
the code. We see that it takes
00:04:06.566
two parameters, m and n. Each of
00:04:09.733
these is mutable, that is, it can
00:04:11.833
be changed within the body of the
00:04:13.466
function, and is of type u64,
00:04:16.933
a 64 bit unsigned integer. The return
00:04:20.566
type of the function is also a u64.
00:04:24.466
You’ll see that Rust requires the types
00:04:26.900
of the function arguments, and the return
00:04:28.766
type if the function returns a value,
00:04:31.366
to be explicitly stated. While it would
00:04:34.266
often be possible for the compiler to
00:04:36.233
infer the types of function arguments and
00:04:38.200
return value, the designers of Rust decided
00:04:41.800
they must always be explicitly stated to
00:04:43.900
avoid confusion, and provide documentation.
00:04:47.466
Within the function body, we see use
00:04:50.033
of the assert() macro, and if and
00:04:52.133
while statements. These all function in the
00:04:54.833
conventional way. The let binding within the
00:04:57.800
if statement creates a local variable binding.
00:05:02.000
You may notice one unusual feature of
00:05:04.066
the function: there is no return statement.
00:05:07.666
Rust distinguishes between statements and expressions.
00:05:11.433
Expressions evaluate to some value; statements have
00:05:14.766
no value. Statements end in semicolons,
00:05:18.400
expressions do not.
00:05:20.733
The gcd() function ends with an expression:
00:05:23.533
n. Like all expressions, it has a
00:05:27.100
value. And, since this value is the
00:05:29.833
last thing in the function, it is
00:05:31.333
returned. This is known as an implicit
00:05:34.233
return, and is a common idiom in Rust.
00:05:37.733
An explicit return, in the form
00:05:39.966
of a return statement, like in other
00:05:41.733
languages, is also possible.
00:05:44.733
Take a copy of the code on
00:05:46.300
the slide. Change the expression at the
00:05:48.166
end of the gcd() function, the line
00:05:51.700
with just n on its own,
00:05:53.666
into a statement by adding a semicolon
00:05:55.866
to the end, and compile the result.
00:05:58.566
Make sure you understand the error message
00:06:00.500
that results, and why it occurs.
00:06:06.033
We’ve seen some of the primitive types
00:06:07.900
available in Rust already. The available types
00:06:11.533
are very similar to those available in
00:06:13.833
C, although the type names are different.
00:06:16.233
The table shows the correspondence.
00:06:19.966
Aside from the names, there are two major differences.
00:06:24.400
The first is that Rust has a
00:06:26.233
native bool type to hold a boolean
00:06:28.433
value, true or false. C does not
00:06:31.566
have a boolean type, and uses integers
00:06:33.633
to represent booleans, with a zero value
00:06:36.333
representing false, and non-zero representing true.
00:06:40.466
The second is the character type.
00:06:43.033
In C, a char is defined to
00:06:45.100
be one byte in size. The number
00:06:47.533
of bits in that byte, and whether
00:06:49.600
it is signed or unsigned are implementation
00:06:51.366
dependent, and the character set is not
00:06:53.833
specified. This makes it difficult to write
00:06:56.966
portable text handling code in C.
00:07:00.733
Rust, on the other hand, defines a
00:07:02.766
char to be a 32-bit Unicode scalar
00:07:05.100
value. This is entirely unambiguous in terms
00:07:08.800
of both the size of the character,
00:07:10.900
and the character set used. This makes
00:07:13.866
it much easier to write portable,
00:07:15.600
and internationalised, text handling code in Rust.
00:07:19.500
Note, though, that while Rust is better
00:07:21.766
than C here, Unicode is still very complicated.
00:07:25.800
In particular, when dealing with text,
00:07:28.133
it’s often necessary to distinguish between the
00:07:30.266
Unicode concepts of scalar values, as used
00:07:33.066
in Rust; code points; grapheme clusters;
00:07:36.600
and characters. It makes sense for Rust
00:07:40.166
to use scalar values for its character
00:07:42.000
type, since these are the basic component
00:07:44.600
of Unicode. But, many things that people
00:07:47.066
recognise as characters, including emoji, are actually
00:07:50.300
Unicode grapheme clusters, represented as sequences of
00:07:54.166
scalar values, and cannot be encoded as a single char.
00:07:58.633
If you want to process text character
00:08:00.933
by character, you probably want to use
00:08:02.866
libraries, such as the Unicode segmentation library
00:08:05.533
mentioned on the slide, that let you
00:08:07.566
work with grapheme clusters, rather than using
00:08:09.666
char values directly.
00:08:14.500
In addition to the primitive types,
00:08:16.600
Rust supports the usual set of compound data types.
00:08:21.100
Arrays work as you might expect.
00:08:23.533
They hold a fixed number of elements,
00:08:25.600
all of the same type. Array bounds
00:08:28.266
are checked at run time.
00:08:32.000
In cases where you need a variable
00:08:33.666
length list, Rust provides a Vector,
00:08:36.166
Vec, type as part of the standard library.
00:08:39.733
The Vec types follows a common pattern,
00:08:42.400
exposing a new() method that creates a
00:08:44.633
new instance of that type, as we
00:08:46.966
see in the example at the top of the slide.
00:08:49.833
What’s notable here is that Vec takes
00:08:52.533
a type parameter, T, that indicates the
00:08:55.166
type of elements it will hold.
00:08:57.500
This parameter has to be specified when
00:09:00.166
creating an empty vector. We see two ways of doing this.
00:09:04.966
The first is to call Vec::new() without
00:09:08.233
specifying the type parameter, but to assign
00:09:11.466
to a variable where the type is specified.
00:09:14.600
The example here specifies that the
00:09:16.533
variable, v, has type Vec, and the
00:09:20.533
new vector is assigned to that.
00:09:23.733
The second way is to explicitly include
00:09:26.033
the type parameter when creating the vector,
00:09:28.900
rather than calling Vec::new(),
00:09:31.966
call Vec::::new().
00:09:37.200
There’s also a convenience macro, that we
00:09:39.466
see at the bottom left, that creates
00:09:41.333
a vector from an array literal.
00:09:44.533
Internally, vectors are implemented as the equivalent
00:09:47.400
of a C program that uses malloc()
00:09:49.333
to allocate space for an array,
00:09:51.266
then realloc() to grow the space when
00:09:53.066
it becomes full. As a consequence of
00:09:56.166
this. conversion from a vector to an
00:09:58.166
array is extremely fast. The vector type
00:10:01.700
implements the Deref trait that provides such
00:10:05.666
a conversion to arrays, allowing vectors to
00:10:07.966
be passed to functions that expect array types.
00:10:14.166
Rust supports tuples, that are collections of
00:10:16.833
unnamed values where each element can be
00:10:18.600
a different type.
00:10:20.833
In this example, the first and last
00:10:23.033
elements of the variable tup are integer
00:10:25.166
values, while the middle element is a
00:10:27.700
floating point value.
00:10:30.400
Elements of a tuple can be accessed
00:10:32.133
by index, starting at zero, using dot notation.
00:10:36.933
Tuples can also be de-structured in a
00:10:39.233
let binding, as we see in the
00:10:41.133
second line of the function on the
00:10:42.566
slide, where the variables x, y,
00:10:45.033
and z are set to the elements
00:10:46.566
of the tuple. This behaviour is similar to that of Python.
00:10:51.966
Rust also permits empty tuple values,
00:10:54.800
as we see at the bottom of
00:10:56.233
the slide. These represent the absence of
00:10:59.300
a value, much like the void type in C.
00:11:04.866
Rust also supports structure types, that are
00:11:08.166
collections of named values, where each element
00:11:10.466
can have a different type.
00:11:13.100
Elements of a struct are accessed using
00:11:15.633
dot notation, as in other languages.
00:11:18.733
Instances of structs are created as we
00:11:21.533
see in the main() function, by specifying
00:11:23.800
the name of the struct, followed by
00:11:25.966
the values for its fields in braces.
00:11:31.000
It’s also possible to specify structs with unnamed fields.
00:11:34.733
These are known as tuple structs.
00:11:37.833
Values of a tuple struct can
00:11:39.666
be accessed in the same way as
00:11:41.166
values of a tuple, and instances of
00:11:43.466
a tuple struct are created by specifying
00:11:45.500
the struct name followed by the values
00:11:47.666
of its fields in parenthesis.
00:11:50.366
Tuple structs can be useful as type aliases.
00:11:55.033
A struct can also be defined that
00:11:57.066
has no elements. These are known as
00:11:59.633
unit-like structs. Since they has no content,
00:12:03.800
unit-like structs takes up no space.
00:12:07.066
They’re useful as marker types or type parameters.
00:12:11.233
We’ll discuss uses of tuple structs and
00:12:13.700
unit-like structs more in lecture 4.
00:12:19.466
Finally, it’s possible to implement methods on a struct.
00:12:23.600
This is done by writing an impl
00:12:25.266
block, specifying the struct to be implemented,
00:12:27.866
as we see on the slide.
00:12:29.966
Method definitions take self as a parameter,
00:12:33.033
representing the struct on which they are
00:12:34.800
implemented. Access to fields of that struct
00:12:38.433
is via explicit self references, like in Python.
00:12:42.800
Methods are called using the dot notation, in the usual way.
00:12:48.200
A struct that implements methods looks a
00:12:50.266
lot like an object in Java or
00:12:52.233
Python. It’s different, though, in that Rust
00:12:55.566
does not support inheritance or subclassing.
00:12:58.866
Instead, it uses a feature known as
00:13:00.966
traits, that we’ll talk about in the next part.
00:13:05.933
That concludes our introduction to the basic
00:13:08.266
operations and types provided by Rust.
00:13:11.100
At this level, Rust is a conventional
00:13:13.266
language, that offers few surprises.
00:13:16.400
In the next part, we’ll move on
00:13:18.200
to discuss traits, enumerations, and pattern matching,
00:13:21.133
that give Rust some more sophisticated behaviours.
Part 3: Introducing Rust (2/4)
The third part of the lecture continues the introduction to the Rust
programming language. It reviews some of the features Rust provides
to support abstraction: traits, enumerated types, and pattern matching.
00:00:00.417
In this part, I’ll move on to
00:00:01.959
discuss some more advanced features of Rust,
00:00:04.750
including traits, enumerations, and pattern matching.
00:00:10.417
Traits are one of the primary ways
00:00:12.250
in which Rust introduces abstraction. They allow
00:00:15.333
you to define a set of operations
00:00:17.291
that can be performed on a type,
00:00:19.000
and to write code that works with
00:00:20.333
any type that implements those operations.
00:00:23.959
A trait defines a set of methods
00:00:25.834
and types. Those methods and types must
00:00:28.542
be implemented by any type that implements that trait.
00:00:32.583
In the code sample on the slide,
00:00:34.417
for example, we see the definition of
00:00:36.834
trait Area. This trait includes the signature
00:00:40.291
of a single method, area(), that takes
00:00:42.959
self as a parameter and return a
00:00:45.000
value of type u32. The body of
00:00:47.917
the method is not specified.
00:00:50.834
The code then defines a struct,
00:00:52.792
Rectangle, with width and height, then implements
00:00:56.417
the trait Area for that struct.
00:00:59.417
The syntax “impl Area for Rectangle” specifies
00:01:02.917
that the Rectangle struct has an implementation
00:01:05.166
of the Area trait, and the body
00:01:07.583
of the impl block contains a definition
00:01:09.625
of the area() method, matching the signature
00:01:12.542
of the method given in the trait definition.
00:01:15.792
Trait definitions usually just include method signatures,
00:01:18.708
as shown here, but they may also
00:01:20.959
include complete method implementations. Methods that have
00:01:24.875
their complete implementation specified in the trait
00:01:27.291
definition do not need to be written
00:01:29.291
in the impl block, but the impl
00:01:31.208
block needs to be present to indicate
00:01:33.083
that the type implements the trait.
00:01:35.708
Traits define functionality.
00:01:38.000
Trait definitions cannot contain
00:01:39.792
instance variables or data; they just specify methods.
00:01:44.375
At this level, traits behave like interfaces
00:01:47.208
in Java, or type classes in Haskell.
00:01:52.542
A trait can be implemented by multiple types.
00:01:56.500
In this example, we show how we
00:01:58.542
can also define a struct Circle,
00:02:00.500
and implement the Area trait for that type too.
00:02:04.125
Both Rectangle and Circle implement the Area
00:02:06.458
trait, and so include an area() method
00:02:08.667
with the same signature. The body of
00:02:11.125
the two methods differs, though.
00:02:14.041
Traits are an important tool for abstraction.
00:02:17.125
They allow you to describe common sets
00:02:19.041
of functionality that can be implemented by different types.
00:02:25.000
Rust is not an object oriented language,
00:02:27.417
and you cannot inherit from a type,
00:02:29.417
or write code that works with subclasses
00:02:31.166
of a particular type. What you can
00:02:33.834
do, though, is write code that works
00:02:35.625
with any type that implements a particular trait.
00:02:39.250
The slide shows the definition of a
00:02:41.250
trait, Summary, that include a single method, summarise().
00:02:45.625
This is followed by definition of a function, notify().
00:02:49.166
The notify() function takes a single parameter,
00:02:52.125
item, of type T. The type,
00:02:55.208
T, is a type parameter.
00:02:58.041
Type parameters are defined in angle brackets,
00:03:00.458
after a function’s name and before its
00:03:02.208
arguments. The definition here indicates that T
00:03:06.166
has type Summary. That is, T is
00:03:09.125
any type that implements the Summary trait.
00:03:12.208
Since all that is known about T
00:03:14.125
is that it implements the Summary trait,
00:03:16.542
the only legal operations on the variable,
00:03:18.750
item, with type T, are those defined
00:03:21.041
on that trait. As we see in
00:03:23.917
the println!() macro, we can call the
00:03:26.083
summarise() method on item, but we can
00:03:28.125
perform no other operations.
00:03:31.250
This approach lets us write generic code.
00:03:34.000
The function, notify(), doesn’t know or care
00:03:36.917
what is the actual type of T,
00:03:38.917
and whether it implements other traits, methods,
00:03:41.375
or instance variables,
00:03:42.959
provided it implements the Summary trait.
00:03:48.000
A number of traits are very widely implemented.
00:03:51.000
For example, the standard library includes the
00:03:53.792
Debug trait that formats a value for
00:03:56.041
printing by a debugger. This is implemented
00:03:59.500
by all the primitive types, and by
00:04:01.166
most other types in the standard library.
00:04:04.750
The Rust compiler understands an annotation,
00:04:07.500
derive, written as shown in the code
00:04:09.583
sample on the slide.
00:04:12.083
The derive annotation can be added to
00:04:14.083
a struct definition, and tells the compiler
00:04:16.917
to generate a standard implementation for the derived type.
00:04:21.250
For example, by writing # [derive(Debug)] on
00:04:24.375
struct Rectangle, as shown, we tell the
00:04:27.792
compiler to auto-generate an "impl Debug for
00:04:30.667
Rectangle" block.
00:04:33.000
This is possible, because every implementation of
00:04:35.708
the Debug trait proceeds in exactly the
00:04:37.708
same way. The code for the impl
00:04:40.333
block can be generated in an entirely
00:04:42.583
mechanical way, and always has the same structure.
00:04:46.792
The first link on the slide points
00:04:48.708
to the list of derivable traits.
00:04:52.083
The second points to a description of
00:04:53.750
how to implement auto-derivation for a trait
00:04:56.000
you might define. While possible, it’s extremely
00:05:00.291
rare to implement auto-derivation for types you define.
00:05:05.959
Using the # [derive(Debug)] annotation, though,
00:05:08.083
is extremely common. This can be used
00:05:10.959
to derive standard traits such as Debug
00:05:13.250
so the object can be printed by
00:05:14.959
a debugger; to implement equality tests for
00:05:17.917
structures, by deriving an implementation of the
00:05:20.291
Eq trait; and to allow copies to
00:05:23.041
be made of objects by deriving the
00:05:25.083
Copy trait, and so on.
00:05:30.000
Finally, traits can include definitions of associated
00:05:32.959
types. That is, that can specify that
00:05:37.250
certain types must be specified when the
00:05:39.417
trait is implemented.
00:05:41.792
For example, for loops in Rust operate
00:05:44.625
on iterators, where an iterator is defined
00:05:47.041
to be something that implements the Iterator trait.
00:05:50.333
The Iterator trait defines a method and an associated type.
00:05:54.917
The method is called next(). It returns
00:05:58.417
the next element in the sequence produced
00:06:00.083
by the iterator, or an indication that
00:06:02.417
there are no more elements. This is
00:06:05.041
an instance of an enum type,
00:06:06.583
Option, that we’ll discuss in a minute.
00:06:09.542
The Option includes a type parameter,
00:06:12.125
Self::Item. This references the other element of
00:06:16.625
the trait definition, a type called Item.
00:06:20.667
What is the Item type? The trait
00:06:23.750
definition doesn’t specify. It indicates that all
00:06:27.500
implementations of the trait need to define
00:06:30.375
the Item type, but otherwise puts no
00:06:32.291
constraint on what it may be.
00:06:34.959
Every Implementation of the Iterator trait must
00:06:37.917
include a line, type Item = something,
00:06:40.917
to specify that type, and must define
00:06:43.500
the next() function to return an optional
00:06:45.458
value of that type. The trait is
00:06:48.417
generic, over any possible type.
00:06:54.000
Traits allow you to write code that
00:06:55.750
operates on many different types, by abstracting
00:06:58.000
away the operations that need to be
00:06:59.667
performed on those types.
00:07:02.458
Enumerated types, enums, allow you to write
00:07:05.500
code that can access the value of
00:07:07.417
data that may be of several different types.
00:07:10.917
In the simplest case, enums work the
00:07:13.333
same way they do in C or
00:07:15.041
Java. They specify a set of named
00:07:17.625
values that an item may take.
00:07:21.750
Rust also allows two more general forms of enum, though.
00:07:25.834
The first is an enum that can
00:07:27.583
hold unnamed data items, like a tuple
00:07:29.917
struct that can take several different variants.
00:07:33.583
In this example, the RoughTime enum can
00:07:36.125
hold values indicating JustNow, InThePast, or InTheFuture.
00:07:41.417
If the value is in the past
00:07:43.208
or future, the enum also holds a
00:07:44.959
time unit and a count.
00:07:47.625
For example, the variable “when” in the
00:07:50.166
code fragment indicates something that happened four
00:07:53.000
score and seven years ago. The InThePast
00:07:56.375
variant of the enum takes two unnamed
00:07:58.500
parameters, a TimeUnit and a number,
00:08:02.708
four score and seven.
00:08:06.166
An enum can also hold named data,
00:08:08.792
acting like a struct that can take
00:08:10.458
several different variants.
00:08:13.083
In this example, the enum Shape,
00:08:15.250
can be either a Sphere, with a
00:08:16.959
centre and a radius, or a Cuboid
00:08:20.000
specified by the locations of two corners.
00:08:25.000
An enum is used when a variable,
00:08:27.375
parameter, or result can have on of
00:08:29.625
several possible types. Enums define the set
00:08:32.834
of possible alternative types for a type,
00:08:35.708
and are used to model data that
00:08:38.125
can take one of a set of related values.
00:08:40.834
Like structs, enums can have type parameters
00:08:43.458
that must be specified when the enum
00:08:45.417
is instantiated. For example, the Rust standard
00:08:48.792
library defines an enum Result, that takes
00:08:51.166
two type parameters, T and E.
00:08:54.792
There are two variants to the Result
00:08:56.750
enum. The Ok(T) variant is used to
00:09:00.500
indicate a successful result, wrapping a value
00:09:03.000
of type T. The Err(E) variant is
00:09:07.667
used to indicate an error, wrapping a result of type E.
00:09:12.333
Enums can also have impl blocks that
00:09:14.834
define methods that can be invoked on
00:09:16.583
the enum, and they can themselves implement traits.
00:09:22.000
The Rust standard library defines two extremely
00:09:24.708
useful standard enum types.
00:09:27.417
One is the Result type, that we
00:09:29.250
saw previously, that’s returned by functions that
00:09:31.667
may either succeed or fail. For example,
00:09:34.750
at the bottom of the slide we
00:09:36.375
see the definition of a recv() function,
00:09:38.875
that returns a Result that can be
00:09:40.500
either Ok, wrapping a value of type
00:09:42.667
Message, or an Err variant that wraps a NetworkError object.
00:09:48.250
The other is the Option type.
00:09:50.500
This represents a value that might not exist.
00:09:53.917
In a C program, for example,
00:09:56.125
one might write a function to lookup
00:09:58.125
a key in a database. This function
00:10:00.625
might take a pointer to the struct
00:10:02.291
representing the database, and a pointer to
00:10:04.917
the key to be found. If the
00:10:07.625
key is found in the database,
00:10:09.250
such a function will return a pointer
00:10:11.333
to the corresponding value, or it will
00:10:13.458
return null if they key doesn’t exist.
00:10:16.959
A Java program would be similar,
00:10:18.708
except that lookup() would be a method
00:10:20.583
on the database object, and would return
00:10:22.667
a reference to an object holding the value, or null.
00:10:26.583
In Rust, the equivalent function would return
00:10:29.625
an instance of the Option type.
00:10:32.083
Option is an enum, that takes a
00:10:33.875
type parameter T, and has two possible variants.
00:10:38.333
Some(T) indicates that the item is
00:10:40.750
present, and None indicates that it is
00:10:43.166
not. The Rust function would therefore return
00:10:46.708
an Option, with the variant indicating whether
00:10:49.792
the result exists or not.
00:10:52.542
This looks like a minor syntactic difference,
00:10:54.917
but as we’ll see later in the
00:10:56.208
lecture, it lets the Rust compiler check
00:10:58.625
for errors much more effectively.
00:11:03.000
The final Rust feature I want to
00:11:04.625
discuss in this part of the lecture is pattern matching.
00:11:08.917
Pattern matching introduces the match statement.
00:11:12.166
This is a generalisation of the switch
00:11:14.208
statement in languages like C and Java.
00:11:17.917
In the simplest case, much like in
00:11:20.417
C, a match statement can match on
00:11:22.875
an integer value. In this example,
00:11:26.458
the count_rabbits() method is called on the meadow object,
00:11:29.500
and the match statement operates on the result.
00:11:33.000
If there are no rabbits, nothing is printed.
00:11:36.375
If there is one rabbit,
00:11:37.667
it prints that a rabbit is nosing
00:11:39.250
around. And if there are several rabbits,
00:11:41.792
it prints to say how many rabbits are hopping about.
00:11:45.583
The last variant shows the first extension
00:11:48.333
of the Rust match statement compared to
00:11:50.625
the C switch statement. A match can
00:11:53.417
include a variable that’s bound if none
00:11:55.250
of the other variants match, and that
00:11:57.625
variable can be used when that branch
00:11:59.458
of the switch statement is executed.
00:12:02.333
A wildcard that doesn’t bind to a
00:12:03.834
value can be specified using an underscore
00:12:07.083
as the value to match.
00:12:09.375
Match statements in Rust are exhaustive.
00:12:11.875
That is, every possible value must match,
00:12:14.583
or there must be a wildcard or variable match.
00:12:18.250
It’s a compile time error if some
00:12:20.125
values are not covered by the match.
00:12:25.000
Rust also generalises the match statement to
00:12:27.625
allow matching on other types, not just integers.
00:12:31.250
The slide shows a match against
00:12:32.750
string values, for example,
00:12:34.333
that evaluate to an enum variant.
00:12:37.708
A match statement in Rust has a
00:12:39.750
value that’s equal to that of the
00:12:41.333
chosen branch. This means it’s possible to
00:12:44.583
use a match statement to assign a
00:12:46.208
value to a variable in a let
00:12:47.583
binding, as shown in the slide.
00:12:51.917
All variants of a match statement must
00:12:53.917
evaluate to give values of the same type, or to nothing.
00:13:01.000
Match statements in Rust
00:13:02.125
can also match against enum variants.
00:13:05.417
On this slide we have the same
00:13:07.333
RoughTime example as used before, with a
00:13:09.917
match statement that checks
00:13:11.208
which variant of the enum is present,
00:13:13.250
and produces a different value in each case.
00:13:17.166
This allows code to be written that
00:13:18.834
can deal with data that can be
00:13:20.417
one of several different variants,
00:13:22.250
one of several different types.
00:13:24.500
Since matches are exhaustive,
00:13:26.417
the compiler will guarantee that all code
00:13:28.458
handles all possible variants.
00:13:32.834
This is extremely useful for writing code
00:13:35.291
that handles optional values and results that may fail.
00:13:39.250
For example, in C one might write
00:13:42.083
a function that looks up a user
00:13:44.000
in a database then books a ticket for that user.
00:13:47.291
The get_user() function returns
00:13:48.792
a pointer to the customer record on
00:13:50.959
success, or null on failure.
00:13:54.291
It’s easy to write code, as shown
00:13:56.875
on the slide, that assumes the get_user()
00:13:59.542
function succeeds and always tried to book
00:14:01.667
the ticket, causing the book_ticket() function to
00:14:04.750
crash when passed a null pointer.
00:14:08.000
C cannot catch the bug at compile time.
00:14:12.250
In Rust, though, the get_user() function will
00:14:15.208
return an instance of the Option enum,
00:14:17.750
and the code will eventually have to
00:14:19.417
pattern match against this to get at the result.
00:14:22.792
The pattern match must be
00:14:24.417
exhaustive, which means that the code won’t
00:14:27.083
compile unless both the Some() and None
00:14:29.375
variants of the Option type are handled.
00:14:32.291
The Rust compiler can’t make you write
00:14:34.625
meaningful error handling, for cases where the
00:14:37.583
get_user() function fails, but it does force
00:14:40.333
you to check for and handle the
00:14:42.083
error somehow, and the code won’t compile
00:14:44.667
if you forget the error handling.
00:14:47.125
Rust therefore turns a runtime failure in C into
00:14:51.125
a compile time check.
00:14:55.000
In this part, I’ve introduced the concepts
00:14:57.625
of traits and enums, that provide abstraction
00:15:00.000
in Rust, and the idea of pattern
00:15:01.917
matching for working with variant data.
00:15:05.125
We’re also now starting to see how
00:15:07.250
the type system can help us write reliable
00:15:09.375
and robust software.
00:15:11.750
The Option and Result enums are small types in themselves,
00:15:15.458
but when used systematically, in combination with
00:15:18.417
exhaustive pattern matching, they remove a common
00:15:21.208
source of bugs: forgetting to check for
00:15:23.667
failures in the return value of function calls.
00:15:27.125
In the next part, we’ll move on
00:15:29.542
to talk about how Rust handles pointers,
00:15:31.834
and start to talk about memory management.
Part 4: Introducing Rust (3/4)
The fourth part of the lecture continues the introduction to the Rust
programming language. It discusses how Rust supports references, and
what constraints it imposes on their use; how memory allocation and
boxing work; and the various string types provided.
00:00:00.375
In this part of the lecture,
00:00:01.917
I'd like to start to discuss
00:00:03.333
one of the more unusual features of Rust,
00:00:06.208
how it handles memory management.
00:00:11.000
At first glance,
00:00:11.834
memory management in Rust looks a little like it does in C.
00:00:16.375
Like in C, the act of taking a reference,
00:00:18.917
a pointer, to an object is explicit.
00:00:22.500
And similarly, so is dereferencing a pointer
00:00:24.750
to access the referenced object.
00:00:27.750
The slide shows how to create a variable binding,
00:00:30.750
let x = 10,
00:00:32.959
and it demonstrates how to take a reference to that binding,
00:00:37.291
let r = &x.
00:00:40.458
In both cases,
00:00:41.375
we see that Rust infers the types of x and r,
00:00:44.959
whereas in the equivalent C code,
00:00:46.917
shown on the right,
00:00:48.083
we have to explicitly write the type.
00:00:51.834
And the terminology is different,
00:00:53.458
with Rust using the term reference,
00:00:55.250
whereas C calls it a pointer.
00:00:58.083
But otherwise, the code is the same.
00:01:02.667
The same is true for dereferencing,
00:01:04.625
where we write let s = *r.
00:01:09.000
The star operator used to dereference pointers,
00:01:12.333
is the same in both languages.
00:01:17.166
Functions can take their parameters by reference.
00:01:19.875
For example, the calculate_length function,
00:01:23.208
shown on the slide,
00:01:24.625
is passing a reference to a buffer
00:01:26.542
rather than passing the buffer itself.
00:01:30.250
This behaves the same as the equivalent C code
00:01:32.458
that passes a pointer to the buffer.
00:01:36.083
Rust is a little more consistent than C here.
00:01:39.125
It uses the & syntax
00:01:40.750
to both take a reference
00:01:42.166
and to pass a reference to a value,
00:01:44.917
while C uses the & syntax to take a reference,
00:01:48.000
but the * syntax to pass a reference.
00:01:51.917
The compiler generates the exact same code
00:01:54.375
for the Rust and C programs in all of these cases.
00:02:01.083
One of the unusual features of Rust
00:02:03.500
is that it distinguishes two different types of reference,
00:02:06.875
immutable references
00:02:08.583
and mutable references.
00:02:12.583
An immutable reference is written using an &,
00:02:15.375
as in the code fragment shown.
00:02:17.875
Let r = &x.
00:02:21.750
An immutable reference
00:02:23.166
is a reference to an object that cannot change.
00:02:26.959
The code fragment,
00:02:28.000
which takes an immutable reference to a variable,
00:02:30.792
then tries to change the referenced value,
00:02:33.250
won't compile.
00:02:35.792
The compiler notices that the reference is immutable
00:02:39.083
and throws an error,
00:02:40.333
indicating that it cannot assign to the referenced value.
00:02:45.667
Sometimes, though, you need to take a mutable reference,
00:02:48.417
a reference that lets you change the referenced item.
00:02:52.500
Rust allows this.
00:02:54.875
Mutable references are written using the syntax &mut,
00:02:58.417
as we see in the second code fragment.
00:03:01.458
They allow the referenced value to change.
00:03:04.583
And if you compile and run the code,
00:03:06.166
you'll see that it prints the value 15,
00:03:08.708
after having successfully changed the value of x
00:03:11.250
via the reference.
00:03:15.875
In addition to the distinction
00:03:17.583
between mutable and immutable references,
00:03:20.667
Rust enforces a number of constraints
00:03:22.834
on how references can be created and used.
00:03:27.208
The first is that a reference in Rust can never be null.
00:03:31.667
A reference always points to a valid object.
00:03:34.166
It's not possible to create or return
00:03:36.500
a null pointer in Rust.
00:03:39.667
Values that would
00:03:41.208
be a potentially null pointer in C or Java
00:03:44.291
are handled by returning an Option type.
00:03:48.458
As we saw in the previous parts of the lecture,
00:03:51.125
this is an enum that either has the value
00:03:53.708
Some(x), where x is the value,
00:03:56.375
or has the value None.
00:03:59.208
The option is extracted using pattern matching,
00:04:02.125
allowing the compiler to enforce the check for the non-case.
00:04:08.625
The second constraint is that while Rust allows many
00:04:11.375
immutable references to an object to exist,
00:04:14.250
it prohibits there from being any mutable
00:04:16.542
references to that object at the same time.
00:04:20.458
And while an immutable reference to an object exists,
00:04:23.875
the Rust compiler enforces
00:04:25.667
that the referenced object is immutable,
00:04:28.041
even if that object was declared to be mutable.
00:04:32.625
This means that you can be absolutely sure
00:04:34.750
that while an immutable reference to an object exists,
00:04:38.166
the referenced object will not change.
00:04:41.834
The compiler enforces this constraint.
00:04:44.917
If you try to write code that has both mutable
00:04:47.375
and immutable references to the same object
00:04:49.708
at the same time,
00:04:51.333
that code will not compile.
00:04:55.583
Further, the compiler enforces
00:04:58.125
that there can be at most one mutable reference
00:05:00.750
to an object in scope
00:05:02.417
and that there can be no immutable references to the object
00:05:05.583
while a mutable reference exists.
00:05:09.625
The compiler also enforces
00:05:11.083
that the original object is inaccessible
00:05:13.333
while the mutable reference exists.
00:05:15.333
If you have a mutable reference to an object
00:05:17.583
you can read or modify that object
00:05:19.542
via the reference and only via that reference
00:05:23.125
and you can be sure that no other
00:05:24.917
part of the program has access to that object.
00:05:30.625
The compiler strictly enforces these guarantees.
00:05:35.083
They limit what type of program you can write,
00:05:37.333
by enforcing the constraints on what references
00:05:40.458
to data can exist at different times.
00:05:44.125
As a consequence, though,
00:05:45.708
these rules make null pointer exceptions,
00:05:48.375
iterator invalidation,
00:05:50.166
and data races between threads
00:05:52.333
impossible in Rust.
00:05:55.208
They trade flexibility for safety.
00:05:58.834
Code that would compile but crash,
00:06:00.917
or throw an exception at runtime,
00:06:03.166
in C, C++, Java,
00:06:05.583
and many other languages
00:06:07.542
simply will not compile in Rust.
00:06:11.166
Code that gives unpredictable undefined behaviour
00:06:14.041
in those languages also in many cases,
00:06:16.917
will not compile in Rust.
00:06:19.959
We'll talk more about this later.
00:06:25.250
In addition to allowing references to existing objects,
00:06:28.667
Rust makes it possible to allocate memory on the heap.
00:06:33.291
In C, memory on the heap is allocated
00:06:35.792
using the malloc() function.
00:06:38.291
This takes as its argument the size of
00:06:40.458
the required allocation and returns a pointer
00:06:43.125
to uninitialized heap memory of the appropriate size.
00:06:48.041
The value can then be stored in the allocated memory
00:06:51.375
by writing to the dereferenced pointer.
00:06:55.041
We see this in the code on the right-hand side
00:06:57.375
of the slide, where the malloc() call allocates space
00:07:00.333
for an integer and assigns this to the variable b.
00:07:04.041
Then, in the next statement, the code
00:07:06.208
writes the value 5 to the allocated space.
00:07:10.875
Rust uses a type known as Box
00:07:13.500
to refer to heap allocated memory.
00:07:17.041
The Box type is a smart pointer type
00:07:19.667
that references an object of type T
00:07:21.959
that's stored on the heap.
00:07:25.208
In the code on the left, the statement
00:07:28.125
let b = box::new(5)
00:07:32.250
creates a new box,
00:07:35.041
while the equivalent C code allocates the memory
00:07:38.166
and then separately assigns a value to that memory.
00:07:41.208
The box::new() function is given the value to be stored
00:07:45.750
and allocates the memory and stores the value in one call.
00:07:50.917
That is when we write,
00:07:52.208
box::new(5),
00:07:54.542
we're not saying allocate 5 bytes of memory,
00:07:58.667
we're saying allocate enough memory to hold an integer
00:08:01.333
and store the integer value 5 into that memory.
00:08:06.250
The implementation of Box is as a pointer to
00:08:09.291
the heap allocated memory.
00:08:11.542
The variable b is represented in exactly the same way
00:08:15.041
in the Rust code and in the C program.
00:08:17.417
The difference is in the way allocation is
00:08:20.041
exposed to the programmer.
00:08:24.166
The result is that memory allocation in Rust is safer
00:08:27.750
than the equivalent in C.
00:08:30.583
There are three reasons for this.
00:08:34.458
First, the value returned by the box::new() call
00:08:38.375
is guaranteed to be initialized.
00:08:41.583
There's no way to read from uninitialized memory in Rust,
00:08:44.959
whereas C allows you to read
00:08:46.750
from the allocated memory before making an assignment,
00:08:50.208
which gives undefined, unpredictable behaviour.
00:08:53.500
Second, the allocation is guaranteed
00:08:55.792
to be the correct size in Rust.
00:08:58.083
The C language makes no attempt to check
00:09:00.375
that the size of the memory allocated by malloc()
00:09:02.750
matches the size of the object
00:09:04.458
stored in that memory,
00:09:05.875
and has undefined and unpredictable behavior
00:09:08.708
if the object is larger than the allocation.
00:09:12.708
And finally, Rust guarantees that the memory
00:09:15.125
will be automatically deallocated
00:09:17.000
when the box goes out of scope.
00:09:19.500
In C, it's necessary to manually call the free() function
00:09:23.250
to deallocate the memory,
00:09:24.917
and it's easy to either forget to free the memory,
00:09:27.625
wasting resources,
00:09:29.417
or to free the memory too early,
00:09:32.083
leading to undefined behavior.
00:09:37.542
By default, a box in Rust is immutable
00:09:40.667
and its contents cannot be changed.
00:09:42.959
A mutable box can be created
00:09:44.917
that does allow the value to change
00:09:46.708
using the "let mut" syntax as shown.
00:09:51.250
Finally, boxes in Rust do not implement
00:09:53.792
the standard Copy trait.
00:09:55.708
This means that you can pass boxes around,
00:09:58.291
but you cannot make copies of them.
00:10:00.333
It's guaranteed that only one copy of a box exists.
00:10:04.500
The Box type is a pointer
00:10:06.959
to memory allocated on the heap.
00:10:09.417
If it were possible to make a copy of the box
00:10:11.750
then it would be possible to create
00:10:13.208
several pointers to the same object.
00:10:16.166
In the same way that Rust prevents you from taking
00:10:19.375
several mutable references to the same object,
00:10:22.500
it also prevents you from creating
00:10:24.125
several pointers to the same object via boxes.
00:10:28.000
And as with mutable references,
00:10:29.875
this is to prevent races between threads.
00:10:35.083
A common case of memory allocation on the heap
00:10:37.250
is to represent strings.
00:10:39.959
Unlike in C, where strings are simply a pointer
00:10:42.417
to a zero terminated array of characters with no
00:10:44.959
specified encoding, strings in Rust
00:10:47.875
are defined to be Unicode text
00:10:50.041
and are encoded in the UTF-8 format.
00:10:53.291
This allows them to represent the full range
00:10:55.583
of internationalized text.
00:10:58.208
Somewhat confusingly,
00:10:59.959
there are two string types in Rust.
00:11:03.458
The first is str.
00:11:05.750
A str is an immutable string slice
00:11:08.625
that's always accessed via an immutable reference as
00:11:11.625
&str.
00:11:13.417
It's built into the language as a primitive type.
00:11:17.500
String literals in Rust, as we see on the slide,
00:11:20.458
are of type &str.
00:11:24.708
In contrast, a string is a mutable
00:11:27.500
string buffer type implemented in the standard library.
00:11:31.625
Essentially, it's a mutable box
00:11:33.583
pointing to an array holding text in UTF-8 format.
00:11:38.458
While the variable of type str cannot change,
00:11:42.041
a string can be modified,
00:11:43.834
and as we see on the slide,
00:11:45.834
and can be created from a string literal.
00:11:49.500
If you're a Java programmer,
00:11:51.500
a string in Rust is equivalent
00:11:53.834
to a string buffer in Java,
00:11:55.542
and the &str type in Rust
00:11:57.959
is equivalent to a Java string.
00:12:00.750
The names in Rust are confusing.
00:12:05.417
Finally, the string type in Rust
00:12:07.041
implements the deref trait from the standard library.
00:12:10.667
This allows the compiler to implement
00:12:12.583
automatic dereferencing for strings.
00:12:16.083
In the example code,
00:12:17.417
the variable s has type String.
00:12:19.917
And if we write let r = &s
00:12:23.250
we get a reference to that string.
00:12:26.000
The variable r has typed &String.
00:12:28.333
It's a reference to a String object.
00:12:31.750
If, instead, we take a reference to s
00:12:34.417
and assign it to the variable t,
00:12:36.125
that we've specified as being of type &str,
00:12:39.542
then the compiler uses the implementation of the deref trait
00:12:42.959
to perform that conversion,
00:12:44.667
giving us an &str, an immutable string slice.
00:12:50.041
This type conversion has no runtime cost,
00:12:52.375
since it just involves taking a pointer
00:12:55.625
to the internal mutable buffer of the string type.
00:13:00.041
The usual Rust rules about immutable references
00:13:02.834
mean that the underlying string becomes unchangeable
00:13:05.834
while the &str reference exists.
00:13:10.458
Since this conversion is free,
00:13:12.333
functions that don't need to mutate the string
00:13:14.750
tend to be only implemented for &str
00:13:16.750
and not on String variables.
00:13:22.375
And that concludes our discussion of memory allocation,
00:13:25.375
boxes, and strings in Rust.
00:13:28.083
In the next part, we'll move on to discussing ownership
00:13:30.875
and how Rust tracks memory allocation,
00:13:33.125
and how it decides when to deallocate memory.
Part 5: Introducing Rust (4/4)
This final part of the lecture discusses how Rust handles ownership and
borrowing of data, and the implications of the ownership rules for
safety and in terms of the complexity of the type system. Finally, it
talks about what makes Rust interesting as a systems language, and what
is novel about its design.
00:00:00.708
In this part of the lecture,
00:00:02.333
I want to discuss one of the more unusual features of Rust,
00:00:05.583
its ownership system.
00:00:08.375
I'll discuss how Rust tracks ownership of values
00:00:11.041
and the implications of this for the way code is structured.
00:00:15.000
And I'll talk about the consequences of the ownership rules
00:00:17.750
and how they change the way Rust programs
00:00:19.834
must be structured.
00:00:24.166
Systems programs care about ownership of resources.
00:00:28.000
This is important for managing memory,
00:00:30.333
but also for managing resources such as files,
00:00:32.959
sockets, locks, and so on.
00:00:36.166
And it's important when implementing state machines,
00:00:38.291
as we'll discuss later in the course.
00:00:42.166
When managing resources,
00:00:43.583
such as memory,
00:00:45.000
a programmer will maintain some mental model
00:00:47.333
of what parts of the code own each resource.
00:00:51.041
In languages like C, for example,
00:00:53.417
with manual memory management,
00:00:55.083
the programmer needs to keep track
00:00:57.166
of what functions call malloc()
00:00:58.834
to allocate memory
00:01:00.041
and where that memory is freed.
00:01:03.166
For every C function that takes a pointer as an argument,
00:01:06.291
the programmer has to know whether that
00:01:07.917
function will free the memory
00:01:09.625
or whether it will leave it
00:01:11.792
for some other function to free.
00:01:15.291
Similarly, every C function that returns a pointer
00:01:18.458
has to make it clear whether that pointer is owned
00:01:20.583
by the library returning it,
00:01:22.375
and will be freed by a later call
00:01:24.250
to one of the library functions,
00:01:26.583
or whether it must be freed by the caller.
00:01:29.959
If the programmer has the wrong understanding,
00:01:32.250
either the program forgets to free memory,
00:01:34.667
leading to a memory leak,
00:01:36.417
or it frees the memory too early,
00:01:38.208
leading to undefined behavior and a segmentation fault.
00:01:43.542
Similar issues exist around
00:01:45.083
management of other resources,
00:01:46.834
such as file descriptors and sockets.
00:01:50.000
It has to be clear who's responsible for
00:01:51.750
closing the file or the connection.
00:01:55.959
Different languages try to address the problem of
00:01:58.125
resource ownership in different ways.
00:02:01.250
Some languages, such as Java,
00:02:03.583
use a garbage collector to manage resources.
00:02:07.000
This prevents resources from being freed too early,
00:02:10.125
but still requires the programmer to understand
00:02:12.834
data ownership to know when to release
00:02:15.125
a reference to an object.
00:02:18.542
This can lead to memory leaks in Java programs
00:02:20.834
if done incorrectly, for example.
00:02:24.500
Other languages, such as C++ and Python,
00:02:27.708
simplify resource management
00:02:29.542
by linking resource lifetime to program scoping rules.
00:02:34.208
For example, the code on the slide
00:02:36.083
shows a Python with statement
00:02:38.083
that opens a file
00:02:39.667
and assigns it to a variable
00:02:41.041
that lives for the duration of the with statement.
00:02:44.708
When the variable goes out of scope
00:02:46.333
the destructor for the object closes the file.
00:02:50.166
This is a powerful approach
00:02:51.708
and gives automatic resource cleanup
00:02:53.583
at the end of the scope.
00:02:57.708
Rust takes a different
00:02:59.375
and more comprehensive approach
00:03:00.875
to managing resources.
00:03:04.458
The Rust compiler and type system
00:03:06.625
track ownership of all data in a program.
00:03:10.708
It enforces that every value in the program
00:03:13.125
has a single owner at all times.
00:03:16.583
To do this, Rust's type system defines rules
00:03:19.750
about the transfer of ownership of data
00:03:21.834
in function and method calls.
00:03:24.834
There are three cases.
00:03:27.875
In the first case,
00:03:29.250
a function that's passed a parameter by value
00:03:31.834
will take ownership of that value.
00:03:34.542
We see this in the consume function on the slide
00:03:37.583
that's passed a resource, R,
00:03:40.166
as its parameter,
00:03:41.250
and takes ownership of that resource.
00:03:44.125
The resource is no longer accessible
00:03:46.208
to the caller once the consume function
00:03:48.166
has been invoked,
00:03:49.083
and is freed once the function completes.
00:03:52.750
The function consumes the resource.
00:03:57.375
In the second case,
00:03:58.625
a function is passed a parameter by reference.
00:04:02.125
This is known as borrowing a value.
00:04:05.166
When a parameter is borrowed in this way,
00:04:08.083
ownership of the resource remains with the caller.
00:04:12.083
The function can use the resource it's
00:04:13.834
borrowed for the duration of the call,
00:04:15.583
but no longer.
00:04:17.708
And when the function returns,
00:04:19.417
the caller still has access to,
00:04:21.166
and ownership of, the resource.
00:04:24.875
This means that a method on a struct
00:04:27.041
that borrows a resource
00:04:28.458
can't store a reference to that resource
00:04:31.583
in the struct for access once the function returns.
00:04:35.792
If you want to keep a reference to a resource,
00:04:37.750
you must consume it rather than borrowing it.
00:04:41.792
The borrow example function on the slid
00:04:43.959
takes an immutable reference to the resource.
00:04:46.917
that allows it to read the resource but not modify it.
00:04:51.542
Borrowing also works with mutable references,
00:04:54.250
written &mut,
00:04:56.125
provided the constraints on references
00:04:58.500
discussed in lecture 3 hold.
00:05:03.041
The final case is a function
00:05:04.458
that can return ownership of a value.
00:05:08.708
In this case, the function gives the resource to its caller,
00:05:11.875
making the caller responsible for freeing that resource.
00:05:16.333
The function or method cannot retain
00:05:18.125
any references to the resource
00:05:19.667
when it gives up ownership in this way.
00:05:25.917
This code sample shows the key features
00:05:28.166
of ownership in Rust.
00:05:31.375
The function main() creates a resource
00:05:33.583
and stores it in a local variable, r.
00:05:37.375
It then passes that resource to the consume() function
00:05:40.083
that takes ownership of the resource.
00:05:43.375
That is, it passes the resource by value
00:05:46.000
to the function.
00:05:48.375
If you try to compile and run this code,
00:05:50.375
you'll find that it doesn't compile.
00:05:53.542
The consume() function takes ownership of the resource,
00:05:56.000
but doesn't pass it back to the caller.
00:05:59.375
Accordingly, when the consume() function returns,
00:06:02.166
the resource is deallocated.
00:06:05.792
Since it gave ownership of the resource
00:06:07.458
to the consume() function,
00:06:09.166
the main() function has no access
00:06:11.250
to that resource thereafter.
00:06:13.959
The println!() call therefore fails.
00:06:16.875
Main() gave away the resource,
00:06:18.500
and doesn't have access to it anymore,
00:06:20.500
so it can't print it.
00:06:24.125
If the main() function called the borrow() function,
00:06:26.417
as defined on the previous slide,
00:06:28.208
instead of consume(),
00:06:29.792
then the code would compile and run.
00:06:32.959
A function that borrows its argument
00:06:35.041
gives it back when it concludes.
00:06:36.917
One that consumes its argument does not.
00:06:43.375
As I said, Rust tracks ownership
00:06:45.208
of data as it's passed between functions.
00:06:49.792
The code on slide is the Rust equivalent
00:06:51.917
of the C program we saw earlier to calculate
00:06:54.166
the conic area.
00:06:57.250
If we look at the lifetimes of the variables
00:06:59.333
in the function area_of_cone(),
00:07:01.542
we see that the variable, r,
00:07:03.792
has a lifetime matching that of the function stack frame.
00:07:07.417
It's allocated when the function starts to execute
00:07:10.125
and goes out of scope and is
00:07:11.792
freed when the function finishes.
00:07:15.000
The variable a, though,
00:07:16.917
is created within the
00:07:18.166
area_of_cone()
00:07:19.750
but then returned from that function.
00:07:22.375
Ownership of the value is passed
00:07:24.333
from that function to its caller,
00:07:26.083
the main() function,
00:07:27.542
and from there it's passed as an argument
00:07:29.583
to the println!() macro
00:07:30.959
that consumes the value.
00:07:34.000
The key point is that
00:07:35.375
the lifetime of the variable,
00:07:37.250
initially stored in the local variable, a,
00:07:39.417
in the area_of_cone() function
00:07:41.417
outlives that function.
00:07:44.667
And the compiler tracks this lifetime.
00:07:48.834
It knows that the ownership has changed.
00:07:51.500
It knows that the value has been passed
00:07:53.125
out of the function into main()
00:07:54.959
and is later consumed by the println!() call.
00:08:01.500
In the example on the previous slide,
00:08:03.500
we saw that ownership of the return value was
00:08:05.959
moved to the calling function.
00:08:09.667
That is, the value is moved into the stack frame
00:08:12.375
of the calling function and assigned to a local variable.
00:08:15.959
And the original value in the called
00:08:18.166
function's stack frame
00:08:19.834
is destroyed when that function returns.
00:08:24.166
If the value being moved is a Box,
00:08:26.250
what's moved is the Box itself.
00:08:29.250
That is, the smart pointer to the heap allocated memory
00:08:32.083
is moved into the stack frame of the caller.
00:08:35.041
The value on the heap that it references is unchanged.
00:08:39.583
Similarly, if a reference is returned,
00:08:41.792
it's the reference that's moved.
00:08:44.208
The referenced value is unchanged.
00:08:49.417
Any variable not returned by a function
00:08:51.375
goes out of scope and is destroyed
00:08:53.417
when the function returns.
00:08:56.750
What does that mean?
00:08:58.208
The compiler inserts the code
00:09:00.000
to call the destructor,
00:09:01.250
the drop() method for the type,
00:09:03.333
followed by a call to free()
00:09:05.083
to deallocate the memory used by the object.
00:09:08.959
If the value going out of scope is a Box,
00:09:11.041
the call to the destructor for the Box itself
00:09:14.000
calls the destructor for the heap-allocated
00:09:15.792
object and then frees the heap memory.
00:09:20.041
Since every object goes out of scope eventually,
00:09:22.250
when it reaches the end of its lifetime,
00:09:24.417
this ensures that all heap memory is freed.
00:09:31.834
Since the Rust compiler tracks
00:09:33.291
the lifetime of every object,
00:09:34.875
it can prevent common lifetime related errors.
00:09:39.500
For example, the Rust program shown on this slide
00:09:42.667
is a function that tries to return
00:09:44.166
a reference to a local variable.
00:09:46.542
This isn't possible since the local variable ceases to exist
00:09:50.041
once the function returns.
00:09:52.917
The compiler notices this and,
00:09:54.792
as we see the code doesn't compile.
00:09:58.125
You can't return a reference to,
00:10:00.166
that is borrow, a value that doesn't exist anymore.
00:10:05.083
The equivalent C program,
00:10:07.166
shown on the bottom of the slide,
00:10:08.959
will compile just fine,
00:10:10.417
but crash at runtime when the returned pointer is used.
00:10:16.041
Good C compilers warn about this in simple cases,
00:10:19.000
like this example,
00:10:20.458
but will compile more complex variants
00:10:22.792
of the code without warnings.
00:10:27.583
Similarly, because the Rust compiler tracks
00:10:29.792
object lifetimes, it can prevent you from accessing
00:10:32.458
memory once it's been freed.
00:10:36.125
The Rust code shown at the top of the slide
00:10:38.083
shows an example.
00:10:40.083
It imports. and explicitly,
00:10:41.959
calls the drop() function
00:10:43.750
to force the local variable, x,
00:10:45.917
to be deallocated.
00:10:49.125
Calling drop() manually
00:10:50.458
is never explicitly needed in Rust,
00:10:52.375
but is possible, and has the
00:10:54.250
same effect as calling free()
00:10:55.917
to deallocate memory in a C program.
00:10:59.583
The Rust code on the slide
00:11:01.125
that deallocates memory
00:11:03.125
then tries to print out the contents
00:11:04.875
of the just deallocated memory
00:11:06.792
fails to compile.
00:11:09.458
The compiler knows that the drop() call
00:11:11.333
consumes the object and that its lifetime ends.
00:11:14.417
It knows that the value cannot then be accessed.
00:11:18.583
The equivalent C program,
00:11:20.083
shown at the bottom,
00:11:21.291
will compile without warnings,
00:11:23.166
but has undefined behaviour at runtime
00:11:25.500
since it accesses previously freed memory.
00:11:32.208
In addition to returning ownership of data,
00:11:34.708
functions can take ownership of a value.
00:11:39.750
When a value is passed to a function,
00:11:41.500
that function takes ownership of that value.
00:11:44.959
We see this in the code on the slide,
00:11:46.792
where the consume() function takes ownership of a
00:11:49.166
local variable, a, from the main() function
00:11:51.708
in the form of its parameter, x.
00:11:54.792
And as usual, once the consume() function ends,
00:11:57.875
the values of any data it owns are not returned,
00:12:01.125
but are rather destroyed.
00:12:04.875
We see this when we try to compile the code.
00:12:07.792
The main() function can't access the local
00:12:09.875
variable, a, to print its length,
00:12:12.250
since it doesn't own the value anymore.
00:12:16.166
It gave ownership to the consume() function,
00:12:18.166
and that function destroyed the value
00:12:19.959
and didn't pass it back.
00:12:22.208
Accordingly, it's no longer accessible in main(),
00:12:24.834
and the code won't compile.
00:12:31.375
We've seen that functions can pass
00:12:33.000
ownership of data between them.
00:12:35.333
We saw how functions take ownership of data they're passed,
00:12:38.041
and how they can return ownership
00:12:39.667
of data to their caller.
00:12:42.750
And we've seen how this relates to memory management,
00:12:45.166
with memory being freed when an
00:12:46.667
object goes out of scope at the end of a function.
00:12:51.166
This works, but repeatedly passing and returning
00:12:54.000
ownership of data to and from functions
00:12:56.500
is inconvenient.
00:12:59.834
To make this easier,
00:13:01.375
Rust augments the ownership rules
00:13:03.375
with the idea of borrowed data.
00:13:07.667
Functions in Rust can take references to data as parameters.
00:13:12.166
For example, in the slide we see the
00:13:14.166
function borrow that takes a mutable reference to a
00:13:16.917
vector x as its parameter,
00:13:19.166
and modifies the vector
00:13:20.917
by pushing a new element onto the end.
00:13:24.792
In the main() function, we create a vector,
00:13:27.542
add some data to it, call the borrow() function,
00:13:30.834
then print the length of the vector.
00:13:34.959
Unlike the case we saw in the last part,
00:13:37.125
where the function consumed the vector,
00:13:39.375
in this case the vector is still accessible
00:13:41.500
after the call to borrow().
00:13:44.750
Why is this?
00:13:47.333
Well because borrow() is passed data by reference.
00:13:51.792
That is, the borrow() function is passed,
00:13:54.208
and takes ownership of,
00:13:55.542
a reference to the vector.
00:13:59.041
It doesn't take ownership of the vector.
00:14:02.875
When the borrow function returns,
00:14:04.959
the lifetime of the parameter, x, ends
00:14:07.583
and is reclaimed in the usual way.
00:14:10.542
The function has taken ownership of that parameter
00:14:12.917
and hasn't returned ownership to the caller,
00:14:15.500
so the data is freed.
00:14:18.458
But what it took ownership of
00:14:20.708
was a reference to the vector,
00:14:22.458
not the vector itself.
00:14:25.250
So what is freed is the reference, not the vector.
00:14:29.333
Ownership of the vector remains with the
00:14:31.208
main() function at all times.
00:14:34.834
This is known as borrowing a reference,
00:14:36.750
and it's important for the ergonomics of Rust programming.
00:14:44.542
This example is a little different.
00:14:47.708
borrow function changes the contents of the vector.
00:14:50.875
It pushes a new element onto
00:14:52.583
the end of the vector.
00:14:55.291
And in this case it's safe for it to do so.
00:14:59.583
But this is not always safe.
00:15:02.959
For example, if main was iterating over the contents of the
00:15:06.583
vector and passed a mutable reference
00:15:09.542
to that vector to a function that modified it
00:15:11.917
while this iteration was in progress,
00:15:14.375
this might lead to elements being skipped
00:15:16.875
or duplicated,
00:15:18.375
or to results to be calculated with inconsistent data.
00:15:23.500
This is a problem known as iterator invalidation.
00:15:30.792
As we discussed in the last part of the lecture,
00:15:33.250
to avoid iterator invalidation and other problems,
00:15:36.291
references in Rust come in two different types
00:15:39.417
and have restrictions on how they can be used.
00:15:43.208
Rust has two different types of pointer,
00:15:45.917
two different types of reference.
00:15:49.500
The first is written &T
00:15:52.000
and is a shared reference to an immutable object of type T.
00:15:57.750
The second is written &mut T
00:16:00.875
and is a unique reference to a mutable object of type T.
00:16:06.792
The Rust compiler and runtime system work together
00:16:10.750
to control how references can be used
00:16:13.000
and to track ownership of references
00:16:14.750
and the referenced values.
00:16:18.417
There are three fundamental rules.
00:16:22.333
An object of type T can be referenced
00:16:24.750
by one or more references of type &T,
00:16:28.667
or it can be referenced by exactly one reference
00:16:32.291
of type &mut T,
00:16:35.083
but it's not possible to have both mutable
00:16:37.542
and immutable references to the same object.
00:16:42.959
If an object is defined to be immutable,
00:16:45.166
it's not possible to take a mutable reference to it.
00:16:49.917
And if an object is defined to be mutable,
00:16:52.417
then taking an immutable reference to that object
00:16:55.792
makes it immutable
00:16:57.583
for the duration of the immutable reference.
00:17:02.125
These restrictions complicate how pointers work in Rust,
00:17:06.208
and they limit the set of programs it's possible to write.
00:17:10.834
but they allow functions to safely borrow objects
00:17:13.708
without needing to give away ownership.
00:17:18.375
In a Rust program, to be able to change an object,
00:17:21.208
you must either own the object
00:17:23.375
and it not be marked as immutable,
00:17:25.542
or you must own the only &mut reference to it.
00:17:31.375
These rules prevent iterator invalidation.
00:17:35.417
Iterators in Rust are designed to take an
00:17:38.083
immutable reference to the object over which they iterate.
00:17:42.000
This guarantees that the object can't change
00:17:44.375
and that no mutable
00:17:46.208
references to the object can exist
00:17:49.125
If the object being iterated over cannot change,
00:17:52.208
the iterator cannot be invalidated.
00:17:55.667
The compiler checks and enforces these rules.
00:18:02.625
Is all the complexity with the different types of reference,
00:18:05.542
and the restrictions on how they're used worthwhile?
00:18:09.000
Yes.
00:18:11.291
By tracking ownership
00:18:12.500
and controlling how references are used,
00:18:15.041
Rust turns various issues that are runtime bugs
00:18:18.000
in other languages
00:18:19.333
into compile time errors.
00:18:22.917
Rust prevents use-after-free bugs
00:18:24.917
by making it impossible to return references
00:18:27.375
to data that outlive the data being referenced.
00:18:31.500
Rust prevents iterator invalidation
00:18:33.583
by making it impossible to change the
00:18:35.417
objects being iterated over while the iterator exists.
00:18:40.041
And Rust prevents race conditions
00:18:41.834
between multiple threads
00:18:43.250
because the rules about pointers make it impossible
00:18:45.708
for two threads to each have a mutable reference
00:18:48.208
to the same object.
00:18:50.959
All these behaviors are checked at compile time.
00:18:55.834
Rust also has efficient runtime behavior.
00:18:59.125
The Rust compiler generates exactly the same code
00:19:02.208
to allocate and free memory
00:19:03.875
as would a correctly written C program
00:19:06.083
using malloc() and free().
00:19:08.708
The difference is that the compiler ensures
00:19:10.708
the malloc() and free() calls are in the correct places.
00:19:14.917
As a result,
00:19:16.041
the timing and memory usage of Rust code
00:19:18.750
is as predictable as a correctly written C program.
00:19:23.917
Rust is deterministic
00:19:26.166
in when memory is both allocated and freed.
00:19:33.166
The memory management scheme used by Rust
00:19:35.083
has some limitations though.
00:19:38.125
Rust ensures correctness by limiting the types
00:19:40.792
of program it's possible to write.
00:19:44.000
The rules about ownership and borrowing
00:19:45.917
make it impossible to express certain data structures
00:19:48.458
in safe Rust.
00:19:50.500
For example, it's not possible to write code
00:19:52.625
that uses data structures that contain reference cycles.
00:19:57.834
The canonical example of this
00:20:00.000
is that it's not possible to write a doubly linked list
00:20:03.000
in safe Rust.
00:20:05.917
If you look at the example on the slide,
00:20:08.166
where you have a list containing elements A, B and C,
00:20:11.792
you'll see that it's not possible to add an element,
00:20:14.333
D, to the end.
00:20:17.708
You can take an immutable reference to element C
00:20:20.583
and add it to element D,
00:20:22.625
and this works since Rust allows
00:20:24.583
two immutable references to C to exist.
00:20:27.333
one from element Band one from element D.
00:20:30.667
00:20:31.417
What you can't do, though,
00:20:32.834
is take a mutable reference to element C
00:20:35.333
in order to modify it
00:20:36.917
to add a reference to element D.
00:20:40.000
This is because there's already an immutable
00:20:42.291
reference to element C
00:20:43.667
held by element B,
00:20:45.708
and you can't have both mutable and
00:20:47.625
immutable references to the same object.
00:20:52.583
The restrictions on references prevent race conditions,
00:20:55.417
iterator invalidation, and so on.
00:20:58.083
But they also prevent cyclic data structures.
00:21:02.500
And it's not just doubly linked lists.
00:21:04.708
They prevent any data structure that
00:21:06.959
contains a loop of references.
00:21:09.917
It's a fundamental limitation of the way
00:21:12.041
references work in Rust.
00:21:14.625
It trades expressive power for safety.
00:21:19.583
The designers of Rust recognized this
00:21:22.458
and added an escape hatch.
00:21:25.291
Rust also has a third type of reference,
00:21:28.041
known as the raw pointer.
00:21:30.917
Raw pointers work just like pointers in C.
00:21:34.834
They allow you to circumvent
00:21:37.000
the restrictions that Rust imposes on mutable
00:21:39.542
and immutable references
00:21:41.375
and make it possible
00:21:42.834
to write cyclic data structures
00:21:44.375
in exactly the same way you would do so in C.
00:21:48.542
Of course,
00:21:49.625
by allowing you to circumvent these restrictions,
00:21:52.208
you lose the safety guarantees of Rust.
00:21:56.583
A Rust program that uses raw pointers
00:21:58.917
is as likely to suffer from memory safety issues,
00:22:01.708
such as use after free bugs,
00:22:03.750
iterator invalidation,
00:22:05.375
and race conditions,
00:22:06.875
as is a C program.
00:22:10.792
To make this clear,
00:22:12.166
Rust requires use of raw pointers
00:22:14.542
to be explicitly labeled as unsafe
00:22:17.208
in the code.
00:22:19.041
It warns the programmer
00:22:20.417
and makes it easy to find such uses.
00:22:25.792
There's a second limitation of safe Rust,
00:22:27.834
which is that it can't express shared ownership
00:22:30.333
to mutable data.
00:22:33.500
Shared ownership of immutable data
00:22:36.083
is straightforward.
00:22:37.834
It's okay for many different references
00:22:40.166
to point to an object that cannot change.
00:22:43.583
Shared ownership of mutable data
00:22:45.917
is problematic though,
00:22:47.500
because it potentially opens up race conditions.
00:22:51.291
This is why Rust only allows a single
00:22:53.583
mutable reference to a value to exist at once.
00:22:57.917
But occasionally, rarely,
00:22:59.875
you need shared mutable state.
00:23:02.834
If you do, Rust has a RefCell type.
00:23:07.792
This wraps some value of type T
00:23:10.208
and dynamically enforces the borrowing rules.
00:23:14.000
That is, it allows callers to borrow,
00:23:16.375
or mutably borrow, the wrapped value.
00:23:19.625
It enforces at runtime
00:23:21.750
that there could only be immutable borrows,
00:23:24.250
or a single mutable borrow,
00:23:26.250
but not both.
00:23:28.917
The RefCell type provides essentially
00:23:31.708
the same guarantees as the regular Rust borrowing rules,
00:23:34.917
but enforced at runtime
00:23:37.083
rather than at compile time.
00:23:40.041
This means that attempts to take, for example,
00:23:42.417
several mutable references to the wrapped object
00:23:45.250
will cause a panic when the code executes,
00:23:47.792
rather than failing to compile.
00:23:51.291
The RefCell is safe,
00:23:52.708
in that it never causes undefined behavior,
00:23:55.750
but it can cause runtime failures.
00:24:01.375
Finally, possibly the biggest consequence of
00:24:04.708
Rust's approach to memory management
00:24:08.583
is that it forces the programmer to consider
00:24:10.792
object ownership explicitly and early in the design.
00:24:16.500
To what extent this is problematic
00:24:18.375
depends, I think, on your background.
00:24:21.834
If you're experienced at programming in C,
00:24:24.166
this tends to be a non-issue.
00:24:27.250
Writing correct C programs also requires
00:24:30.041
careful consideration of data ownership,
00:24:32.458
to know what functions malloc() data
00:24:34.750
and what functions free() that data.
00:24:38.250
Rust essentially codifies and enforces
00:24:40.917
the rules that well-written C programs
00:24:42.834
tend to adopt anyway.
00:24:45.667
However, if your experience is with a
00:24:47.792
language like Python or Java,
00:24:50.041
where the use of a garbage collector
00:24:52.125
or reference counting hides a lot of the
00:24:53.792
complexity of memory management,
00:24:56.208
then needing to start thinking about
00:24:57.959
ownership is more of a burden.
00:25:01.041
In this case, programming effectively
00:25:03.417
in Rust may require a shift in your thinking.
00:25:10.250
That concludes our initial review of the
00:25:11.959
Rust programming language.
00:25:14.875
As should be clear,
00:25:16.208
Rust is largely a normal systems language.
00:25:20.542
The basic types, control flow,
00:25:22.708
and data structures are very familiar
00:25:24.750
to programmers coming from other languages.
00:25:28.250
But it does make some innovations for a systems language.
00:25:32.875
Enumerated types and pattern matching
00:25:35.083
are well-known features of functional programming languages,
00:25:38.750
as are the option and result types,
00:25:41.750
but they've not previously been used in systems programming.
00:25:47.417
Similarly, the use of structures and traits
00:25:49.667
as an alternative to object-oriented programming
00:25:52.333
mirrors the use of type classes in Haskell,
00:25:54.875
but it's new in the systems domain.
00:26:00.583
Overall, there's relatively little in Rust
00:26:03.291
that is truly novel.
00:26:06.083
The syntax is a little different from that of C,
00:26:08.959
but where it differs,
00:26:10.458
it mostly takes inspiration from Standard ML.
00:26:14.667
The basic data types closely match those of C,
00:26:18.000
and enumerated types and pattern matching
00:26:20.667
also come from the Standard ML language.
00:26:25.083
Standard ML was an influential
00:26:26.959
functional programming language,
00:26:28.834
developed back in the 1980s,
00:26:31.959
that was widely used for teaching functional programming
00:26:34.417
before Haskell was developed.
00:26:36.750
It would be familiar to people,
00:26:38.708
like Graydon Hoare, who first designed Rust,
00:26:42.083
who learnt programming some decades ago.
00:26:46.792
Rust traits are adapted from the Haskell type classes,
00:26:49.750
and there are many influences from C++,
00:26:52.625
but these are generally of the form of looking at
00:26:54.792
how C++ solves a problem
00:26:56.542
and doing the opposite.
00:26:58.917
Rust tends to favour the safe default,
00:27:01.417
while C++ tends to favour performance
00:27:04.708
and makes the safe choice an option.
00:27:09.083
The one area where Rust is novel
00:27:11.208
is in its memory management.
00:27:13.750
The ideas around references and ownership
00:27:15.959
that we've touched on in this lecture,
00:27:17.583
and we'll talk more about later in the course,
00:27:19.667
are unique to Rust.
00:27:22.250
Although even here,
00:27:23.375
they're influenced by previous work
00:27:25.000
on a research language known as Cyclone,
00:27:27.208
developed by AT&T and Cornell University
00:27:30.166
in the early 2000s.
00:27:35.917
What makes Rust an interesting language?
00:27:39.750
Well, it employs a safe, modern type system.
00:27:43.917
It has no concept of undefined behaviour,
00:27:46.500
and it's memory safe.
00:27:49.291
Rust programs don't suffer from undefined behaviour
00:27:52.083
due to buffer overflows, dangling pointers,
00:27:54.500
or null pointer dereferences.
00:27:58.375
And the type system is expressive enough,
00:28:00.583
with enough zero-cost abstractions,
00:28:02.583
that it can be used to model the problem space
00:28:05.166
and check designs for consistency,
00:28:07.125
as we'll discuss later.
00:28:12.125
Rust is interesting because it has a type system
00:28:14.375
that can model data and resource ownership.
00:28:17.750
It provides deterministic,
00:28:19.333
automatic, memory management
00:28:21.083
that prevents iterator invalidation,
00:28:23.166
use after free bugs, and most memory leaks.
00:28:26.667
And that lets us model state machines,
00:28:28.583
and resource usage in state machines,
00:28:30.417
in a way that makes it easier to validate
00:28:32.708
system designs for correctness.
00:28:35.125
We'll talk more about these in later lectures.
00:28:39.000
And Rust has rules around references
00:28:40.959
and ownership that prevent data races
00:28:42.667
in concurrent code,
00:28:44.041
that enforce the design patterns
00:28:46.083
that are common in well-written C programs.
00:28:49.417
And again, we'll talk more about this in future lectures.
00:28:54.917
And fundamentally,
00:28:56.500
Rust is a systems programming language
00:28:58.458
that eliminates many classes of bug
00:29:01.208
that are common in C and C++ programs
00:29:05.625
and makes it easier to write correct software.
00:29:12.208
That concludes this lecture.
00:29:14.375
I've discussed what is a strongly typed language
00:29:17.417
and hopefully shown you why it's desirable.
00:29:20.708
I've begun to introduce the Rust language,
00:29:23.166
which is one example of a modern,
00:29:25.250
strongly typed systems programming language
00:29:27.667
that we'll use to illustrate the benefits
00:29:29.792
of strong typing for systems programming.
Discussion
Discussion will include presentation and discussion of the slides you
prepared in lab 2, considering the energy efficiency of programming
languages and their impact on the carbon footprint of a system, plus
a review of the material in Lecture 3.
The lecture focussed on the definition of a type system and of strongly
typed languages. It discussed the benefits of strongly typed languages,
and introduced the Rust programming language as an example of a modern,
strongly typed, systems programming language.
You should review what are type systems and how they differ between the
various programming languages you have used. Think about strongly and
weakly typed languages in the context of safe and unsafe programming.
A safe language, whether static or dynamic, knows the types of all the
variables and only allows legal operations; results of a program using
only strong types are well-defined. An unsafe language, on the other
hand, allows the types to be circumvented to perform operations the
programmer believes correct, but the type system can’t prove to be so.
Think about what is the trade-off between safe and unsafe languages
for systems programming? Can systems programs be written entirely
in a safe language, or is some escape hatch into unsafe behaviour
needed?
The lecture started to introduce the Rust language and explore what
features it has that are familiar and what are less so.
In particular, it focussed on how the language tracks ownership of data
as it moves between functions, and how it deterministically cleans up
heap allocated memory when the lifetime of an object ends.
From what you have seen so far, does Rust provide the right set of
features for a systems languages? How does it compare with other
languages you've used? Do you understand how ownership and memory
management work in Rust?