csperkins.org

Advanced Systems Programming H (2020-2021)

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 language.

Part 1: Types and Systems Programming

The 1st 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.000 In this lecture, I want to move

00:00:02.597 on from the general discussion of the

00:00:05.194 problems with systems programming, and talk about

00:00:07.792 types and systems programming in more specific

00:00:10.389 terms.

 

00:00:10.860 In particular, I want to talk about

00:00:13.287 strongly typed languages, talk a bit about

00:00:15.715 what is a strongly typed language ,

00:00:18.142 why strong typing is desirable, and how

00:00:20.569 we can make use of types for

00:00:22.996 systems programming.

 

00:00:23.790 And I want to move on and

00:00:25.732 start to introduce the Rust programming language,

00:00:27.674 talking about the basic operations and types

00:00:29.616 that are feasible in that language,

 

00:00:31.380 the way it does pattern matching and

00:00:34.825 memory management, and finally talk a bit

00:00:38.269 about why Rust is interesting as a

00:00:41.714 systems programming language.

 

00:00:43.290 To begin, I want to talk about

00:00:45.939 strongly typed languages. I want to talk

00:00:48.588 about what is strongly typed language,

00:00:50.859 why it's desirable, and how types can

00:00:53.508 be used for systems programming.

 

00:00:55.500 So first of all, what is a

00:00:57.906 type?

 

00:00:58.350 Well, a type in programming languages is

00:01:01.312 something which describes what an item of

00:01:04.274 data represents.

 

00:01:05.220 It tells us whether a particular variable

00:01:07.828 can hold an integer, a floating point

00:01:10.436 value, a file, a sequence number,

00:01:12.671 a username, or whatever it happens to

00:01:15.279 be. It says conceptually what is the

00:01:17.887 data which is represented by a variable,

00:01:20.495 and how is that data represented?

 

00:01:22.830 Types are very familiar in programming.

00:01:24.496 For example, if we look at the

00:01:26.440 code on the right hand side of

00:01:28.384 the screen, which is C code,

 

00:01:30.150 we see a number of variable declarations.

00:01:32.301 We can specify the types of the

00:01:34.453 variable.

 

00:01:34.860 We specify that x holds an integer,

00:01:37.032 for example; that y holds a double

00:01:39.203 precision floating point value; and that the

00:01:41.375 variable hello is a pointer to a

00:01:43.547 character, in this case a pointer to

00:01:45.718 the first character of the string “Hello,

00:01:47.890 world”.

 

00:01:48.300 We also see that it’s possible to

00:01:50.950 define new types. For example, the definition

00:01:53.601 of the struct, struct sockaddr_in, on the

00:01:56.251 slide

 

00:01:56.730 defines a compound type holding five fields:

00:01:59.598 length, family, port, addr, and some padding.

00:02:02.466 Each of which has its own type,

00:02:05.334 and the type of one of these

00:02:08.202 is, in turn, a compound type,

00:02:10.661 struct in_addr.

 

00:02:11.580 This lets us build up reasonably complex

00:02:14.230 types, to represent the different types of

00:02:16.881 data that we’ll work with in our

00:02:19.531 program.

 

00:02:20.010 So given this definition of a type,

00:02:22.231 what is a type system? Well,

00:02:24.134 a type system is a set of

00:02:26.355 rules that constrains how the types can

00:02:28.576 be used.

 

00:02:29.310 The type system specifies what operations can

00:02:32.050 be performed on particular types of data.

 

00:02:34.890 What operations can be performed with those

00:02:38.025 types of data, and how the different

00:02:41.160 types of data compose with other types

00:02:44.295 of data to form compound data types,

00:02:47.431 or types specifying different alternatives.

 

00:02:49.770 A type system specifies what the program

00:02:52.643 can do. It specifies the legal behaviour

00:02:55.517 for objects of those particular types.

 

00:02:58.080 Equally, it proves that the program can't

00:03:01.048 do certain things. It proves that the

00:03:04.016 program can't perform certain illegal behaviorus.

 

00:03:06.660 This doesn't guarantee that the program is

00:03:09.403 correct, of course, but it does guarantee

00:03:12.147 that some types of incorrect behaviour don't

00:03:14.890 occur in a well-typed program.

 

00:03:16.950 Type systems eliminate certain classes of bugs,

00:03:19.771 hopefully without adding too much complexity to

00:03:22.592 the language. Some of the bugs the

00:03:25.413 type system helps us prevent are straightforward.

00:03:28.235 It prevents us adding apples to oranges

00:03:31.056 and getting a meaningless meaningless answer,

00:03:33.474 for example.

 

00:03:34.380 Or it guarantees that we can't access

00:03:36.912 the 11th element of the collection,

00:03:39.082 which only holds 10 elements. Some type

00:03:41.614 systems can help protect against more subtle

00:03:44.147 bugs, though.

 

00:03:44.970 Modern type systems, for example, can help

00:03:47.394 make sure that race conditions don't occur

00:03:49.818 in multi threaded code. Or they can

00:03:52.243 check various invariants of the program behaviour,

00:03:54.667 and check that particular features of the

00:03:57.091 design are upheld.

 

00:03:58.230 The goal of designing a type system

00:04:00.623 is to balance complexity, through the complexity

00:04:03.016 and the features of the type system,

00:04:05.409 with the ability to catch bugs.

 

00:04:07.560 A badly designed type system adds complexity

00:04:10.426 and syntactic overhead to the language,

00:04:12.883 but doesn't really really catch any problems.

00:04:15.749 Some would suggest that the type system

00:04:18.615 in languages like Java is in this

00:04:21.481 category.

 

00:04:21.990 Ideally what we want, though, is a

00:04:24.387 language where the type system is sophisticated

00:04:26.784 enough to catch real problems with the

00:04:29.181 code, yet low enough overhead that people

00:04:31.578 are willing to use it.

 

00:04:33.390 Types are a fundamental feature of a

00:04:35.608 program. We’re used to thinking of types

00:04:37.825 as a compile time feature because the

00:04:40.042 compiler complains when we get them wrong.

 

00:04:42.360 But types exist at runtime too,

00:04:44.690 and certain types of type checking also

00:04:47.407 happen at runtime. For example, array bounds

00:04:50.125 checks are very much a property of

00:04:52.843 an array type, but are typically checked

00:04:55.561 at runtime, rather than compile time.

 

00:04:57.990 Different languages have different type systems.

 

00:05:01.470 Some languages are strongly type, and provide

00:05:04.279 no flexibility, no escape from the type

00:05:07.089 rules.

 

00:05:07.590 In others, the type checking is much

00:05:09.979 weaker, and it's possible to subvert the

00:05:12.368 rules or to cast between different types

00:05:14.757 of data.

 

00:05:15.540 Some languages apply types statically, and when

00:05:17.834 a variable is assigned a particular type,

00:05:20.128 its type can never change and it

00:05:22.423 can only hold variables of, hold values

00:05:24.717 of, that type.

 

00:05:25.800 Other languages are more dynamic, and allow

00:05:28.717 the types that variables can hold to

00:05:31.633 change at different points in the program.

 

00:05:34.650 There are different trade offs here.

00:05:36.220 There's no right or wrong answer.

 

00:05:37.890 And when we're thinking about type systems,

00:05:40.696 we need to think about, to what

00:05:43.502 extent the typing rules are strictly enforced,

00:05:46.308 and to what extent objects can change

00:05:49.114 their types as the program’s execution proceeds.

 

00:05:52.020 In a language with static types,

00:05:53.930 the type of a variable is fixed.

00:05:56.158 In the example at the bottom of

00:05:58.387 the slide, for example,

 

00:05:59.760 we have a Rust program which declares

00:06:02.130 the variable x to hold an integer

00:06:04.499 type and then tries to add the

00:06:06.869 floating point number 4.2 to it.

 

00:06:09.000 And since Rust is a statically typed

00:06:11.476 language, this fails and the compiler complains

00:06:13.952 that you can't add a floating point

00:06:16.428 number to a value which is holding

00:06:18.904 an integer type. The types don’t match.

 

00:06:21.480 What's interesting in this example, though,

00:06:23.485 is that we never specified that the

00:06:25.825 variable x holds an integer type

 

00:06:27.930 Some statically typed languages require that the

00:06:30.793 types of variables are explicitly declared.

00:06:33.248 C and C++ and Java fall into

00:06:36.111 this category, for example. Other, like Rust,

00:06:38.974 and like the example we see on

00:06:41.838 the slide, can infer types from the

00:06:44.701 context.

 

00:06:45.210 However, just because the language can infer

00:06:47.434 the type of variable doesn't mean that

00:06:49.659 that type is dynamic.

 

00:06:51.030 With rust, once the type of variable

00:06:53.586 x has been inferred to be an

00:06:56.141 integer we can't add a floating point

00:06:58.697 value to it, even though we never

00:07:01.253 explicitly said that x can hold integers.

00:07:03.808 The type is still static, it just

00:07:06.364 saves us the typing of specifying what

00:07:08.920 it is.

 

00:07:09.750 In other languages, the types are much

00:07:12.356 more dynamic.

 

00:07:13.200 The example show some Python code.

00:07:15.049 And again, we set a variable x

00:07:17.207 the hold the value six. We inspect

00:07:19.364 its type, and we see that its

00:07:21.521 type is an integer. And again,

00:07:23.371 Python has inferred the type in much

00:07:25.528 the same way that Rust did in

00:07:27.685 the previous slide.

 

00:07:28.710 However in this case, when we add

00:07:30.791 the value 4.2 to it, which is

00:07:32.871 a floating point value, it succeeds.

00:07:34.655 And if we look at the type,

00:07:36.735 we inspect the type of x,

00:07:38.519 we see that its type has changed

00:07:40.599 to that of a floating point number

 

00:07:42.780 In Python types of dynamic, and it's

00:07:45.626 safe to convert an integer to a

00:07:48.472 floating point value, it doesn't lose any

00:07:51.318 information, so when we ask the interpreter

00:07:54.164 to do so, the conversion succeeds and

00:07:57.010 the type of the variable changes.

 

00:07:59.550 Which is better, a dynamically typed language

00:08:03.133 or statically typed language?

 

00:08:05.280 Well, it very much depends what you're

00:08:07.195 doing, and there are different trade offs.

 

00:08:09.210 Dynamically typed languages tend to perhaps be

00:08:12.190 lower performance, but they offer more flexibility.

 

00:08:15.270 A dynamically typed language has to store

00:08:17.336 the type of a variable as well

00:08:19.403 as its value at runtime. And this

00:08:21.469 tends to take up additional memory.

 

00:08:23.340 It also has to check that the

00:08:25.356 variables are of the correct type before

00:08:27.373 it performs the various operations, and it

00:08:29.389 has to perform those checks at runtime.

00:08:31.406 Again, because the types can change over

00:08:33.422 time.

 

00:08:33.810 And similarly, it can make fewer optimisations

00:08:36.567 based on the types of the variable,

00:08:39.323 again because the types of can change.

 

00:08:42.180 Systems languages tend to have static types,

00:08:44.717 and they tend to be compiled ahead

00:08:47.255 of time, because they’re performance sensitive.

 

00:08:49.530 If the types of fixed, and if

00:08:51.493 that the compiler can look at code

00:08:53.456 and make optimisation decisions based on the

00:08:55.420 code,

 

00:08:55.800 and can do so ahead of time,

00:08:59.158 without worrying about performing those optimisations quickly,

00:09:02.516 it can generally achieve better performance.

00:09:05.394 Systems programming languages tend to trade-off performance

00:09:08.752 for flexibility, and have very static type

00:09:12.110 systems.

 

00:09:12.690 In a language with strong types,

00:09:14.884 every operation must conform to the type

00:09:17.444 system.

 

00:09:17.910 A strongly typed language makes sure that

00:09:20.270 operations which can't be proven to be

00:09:22.630 correct, that can't be proven to conform

00:09:24.990 to the typing rules, are not permitted.

 

00:09:27.450 More weakly type languages provide ways of

00:09:30.575 circumventing the type checker.

 

00:09:32.460 For example, a lot of languages allow

00:09:35.375 safe conversions, safe and automatic conversions,

00:09:37.873 between certain types. For example, a lot

00:09:40.787 of languages allow conversions between floating point

00:09:43.702 and double precision types, to extend the

00:09:46.616 precision of a type, or from an

00:09:49.531 integer to a

 

00:09:50.880 long integer

 

00:09:52.830 And in all these cases the conversion

00:09:55.319 is safe.

 

00:09:56.130 In other cases, the language can allow

00:09:58.555 more open-ended casts. The code fragments at

00:10:00.980 the bottom of the slide shows a

00:10:03.404 common idiom in C.

 

00:10:04.890 The variable, buffer, holds an unstructured sequence

00:10:07.803 of characters, and the recv() call reads

00:10:10.716 data into that buffer.

 

00:10:12.480 Once the read has successfully retrieved that

00:10:15.297 data, it’s cast to a different type

00:10:18.113 representing the expected contents of the buffer.

 

00:10:21.030 This is very unsafe behaviour. The programmer

00:10:23.669 is essentially telling the compiler “Trust me,

00:10:26.308 I know what I’m doing”. Trust that

00:10:28.946 this sequence of bytes is actually,

00:10:31.208 in this example, an RTP packet.

 

00:10:33.570 If the programmer is correct, and the

00:10:36.243 sequence of bytes really is an RTP

00:10:38.916 packet, this is safe and high performance.

00:10:41.589 If the programmer is not correct,

 

00:10:43.980 the data doesn't match its type,

00:10:47.084 and the behaviour is undefined.

 

00:10:49.770 A weakly type language provides these sort

00:10:52.565 of escape hatches. Ways of circumventing the

00:10:55.359 type system. Ways of telling the compiler

00:10:58.154 “Trust me, I know what I'm doing”.

00:11:00.948 This can provide a lot of power.

00:11:03.743 It's also very risky because if the

00:11:06.537 program and gets it wrong, the program

00:11:09.332 crashes unpredictably

 

00:11:10.230 When thinking about strong and weak types,

00:11:12.967 it’s essentially important to them in the

00:11:15.704 context of safe and unsafe languages.

 

00:11:18.150 A safe language, whether the typing is

00:11:20.712 static or dynamic, knows the types of

00:11:23.275 all the variables, and only allows legal

00:11:25.837 operations on those values at any time.

 

00:11:28.500 An unsafe language, on the other hand,

00:11:30.822 unless the types to be circumvented.

00:11:32.812 It allows the programmer to specify to

00:11:35.134 the compiler “Trust me, I know what

00:11:37.457 I'm doing”.

 

00:11:38.220 It lets the programmer perform operations which

00:11:40.618 they believe to be correct, even though

00:11:43.017 the type system can't prove them to

00:11:45.415 be so.

 

00:11:46.200 It pushes the burden of checking for

00:11:49.081 correctness onto the programmer, rather than allowing

00:11:51.962 the type system to help.

 

00:11:54.120 Unsafe languages provide a lot of flexibility.

00:11:56.626 They allow you to do things which

00:11:59.132 are not possible in safe languages.

 

00:12:01.380 They’re also much riskier. It's much easier

00:12:04.926 to mess up in an unsafe language,

00:12:08.471 and to have the program crash.

 

00:12:11.610 And this is why strong typing is

00:12:14.026 desirable, I think. Results for a program

00:12:16.442 that only use strong types are always

00:12:18.858 well defined. The language is always safe.

00:12:21.274 The results are always consistent with the

00:12:23.689 rules of the language.

 

00:12:25.170 A strongly typed program only ever performs

00:12:28.205 operations that are legal. It can never

00:12:31.239 perform undefined behaviour.

 

00:12:32.640 Strong typing helps us model the problem

00:12:35.235 space. It helps us check out designs

00:12:37.830 and the resulting code for consistency.

00:12:40.055 It helps eliminate certain classes of bugs.

 

00:12:42.750 That is, the type system can't prove

00:12:45.365 that the program is correct, but it

00:12:47.980 can prove that certain behaviours don't happen

00:12:50.595 because they're not legal for those types.

 

00:12:53.310 Weekly type system, on the other hand,

00:12:56.402 can't make such guarantees, because the programmer

00:12:59.494 always has the option of circumventing the

00:13:02.587 type system.

 

00:13:03.570 We've all seen this message, segmentation fault

00:13:07.248 (core dumped), when writing C programs.

 

00:13:10.500 I'd argue, though, that segmentation faults should

00:13:13.596 never happen.

 

00:13:14.580 The compiler and the runtime should be

00:13:17.265 able to enforce the typing rules,

00:13:19.567 and make sure that if the program

00:13:22.252 violates them, it's terminated cleanly.

 

00:13:24.270 A segmentation fault happens when the program

00:13:27.241 is not terminated cleanly, and the program

00:13:30.211 perform some behaviour which is illegal,

00:13:32.758 accesses memory which it doesn't own,

00:13:35.304 and the operating system kills it.

 

00:13:37.950 That's a useful safety measure. It's important

00:13:40.869 that the operating system can stop wayward

00:13:43.787 programs. Unfortunately, it's not a very precise

00:13:46.706 safety measure.

 

00:13:47.640 There are lots of behaviours which access

00:13:49.977 memory outside the bounds of an object,

00:13:52.315 but which don't go outside the bounds

00:13:54.652 of memory allocated by the operating system.

 

00:13:57.090 These give undefined behaviour. They silently corrupt

00:14:00.343 and modify other parts of the program’s

00:14:03.596 state. It’s these types of types of

00:14:06.850 misbehaviour that tend to lead to security

00:14:10.103 vulnerabilities, as a result of undefined behaviour

00:14:13.356 due to weak type systems.

 

00:14:15.780 The C programming language is especially bad

00:14:19.070 for this. The C standard documents 193

00:14:22.360 different kinds of undefined behaviour in the

00:14:25.650 language.

 

00:14:26.220 And I think what's more worrying is

00:14:28.626 that any of these undefined behaviours can

00:14:31.032 lead to entirely unpredictable results.

 

00:14:32.850 If the program hits undefined behaviour,

00:14:35.284 the standard says anything can happen.

00:14:37.718 It doesn't make any guarantees. That's really

00:14:40.558 worrying if we're trying to write secure,

00:14:43.397 correct, and trustworthy code.

 

00:14:45.120 The link on the slide, to the

00:14:48.470 blog post, points to some discussion of

00:14:51.821 this. And it's really quite alarming the

00:14:55.171 sorts of behaviours that C programs can

00:14:58.521 perform.

 

00:14:59.100 As we've seen, C is a weakly

00:15:01.944 type language, yet it's widely used for

00:15:04.788 systems programming.

 

00:15:05.700 Why is this, why do we use

00:15:08.317 a language which provides so few guarantees?

00:15:10.934 And can we write systems programs in

00:15:13.550 languages which are strongly typed? And what

00:15:16.167 are the difficulties in doing so?

 

00:15:18.510 Well, I think, the question is why

00:15:21.487 C is weakly typed is a historic

00:15:24.465 accident.

 

00:15:24.990 Partly is because the original designers of

00:15:28.196 C were not type theorists. They were

00:15:31.402 operating systems designers, rather than programming language

00:15:34.608 designers, programming language theorists.

 

00:15:36.540 In part, it's because of the machines

00:15:38.877 and which C was developed didn't have

00:15:41.213 the resources to perform complex type checks.

 

00:15:43.650 Even if the people designing the language

00:15:46.047 had been experts in programming language theory,

00:15:48.444 and even if we had had sophisticated

00:15:50.841 type systems and the ability to perform

00:15:53.238 such checks, the machines they were running

00:15:55.636 the code on, didn't have the resources

00:15:58.033 to do that.

 

00:15:59.160 In part because type theory wasn't particularly

00:16:02.016 well advanced in the early 1970s,

00:16:04.465 when C was being designed. We didn't

00:16:07.321 know how to perform the various checks

00:16:10.178 that are possible today.

 

00:16:11.910 Is strongly typed systems programming feasible?

 

00:16:15.270 Well, yes, I think it is.

00:16:17.337 In fact, there's been many examples of

00:16:19.749 operating systems which are written in strongly

00:16:22.161 typed languages.

 

00:16:22.950 The original version of the Mac operating

00:16:25.555 system, for example, was written in Pascal.

 

00:16:28.260 Was a research project in the 80s

00:16:31.004 known as project Oberon, which used a

00:16:33.748 language called Oberon, a descendant of Pascal

00:16:36.492 to write operating systems.

 

00:16:38.160 And the US Department of Defence developed

00:16:41.037 the Ada programming language for aerospace,

00:16:43.503 military applications, and air traffic control,

00:16:45.968 and that's very much a strongly typed

00:16:48.845 language designed for systems programming.

 

00:16:51.000 The code fragment on the right is

00:16:53.237 a sample of Ada code. And we

00:16:55.475 see that it very precisely specifies the

00:16:57.712 ranges of the various numeric types.

 

00:16:59.730 It specifies that the order in which

00:17:02.524 fields are packed into the various control

00:17:05.318 registers. It even specifies the byte order

00:17:08.111 of the types. In some ways it

00:17:10.905 provides even more low level control than

00:17:13.699 C does, although perhaps in a much

00:17:16.493 more verbose way.

 

00:17:17.790 Over the years the popularity of C

00:17:20.403 and Unix has kind of led to

00:17:23.017 a belief that operating systems require unsafe

00:17:25.630 weakly type code.

 

00:17:26.850 That may be true at the very

00:17:29.865 lowest levels; programming interrupt registers, programming particular

00:17:32.880 hardware registers, but most systems code,

00:17:35.465 including most device drivers, can pretty much

00:17:38.480 be written in strongly typed safe languages,

00:17:41.495 with only tiny fragments of unsafe code.

 

00:17:44.610 The Rust programming language is a modern

00:17:47.461 attempt to try and provide a type

00:17:50.312 safe language which is suitable for systems

00:17:53.163 programming.

 

00:17:53.670 What I hope to show in this

00:17:56.212 course, is that this is very much

00:17:58.755 achievable, and we can use safe languages

00:18:01.297 to write systems programs.

 

00:18:02.850 What I've done in this lecture.

00:18:05.008 I've spoken a little bit about what

00:18:07.527 is a strongly typed language, and the

00:18:10.045 differences between strong and weak typing,

00:18:12.203 and static and dynamic typing, and the

00:18:14.722 differences between safe and unsafe languages.

 

00:18:16.980 I’ve hopefully explained why strong typing is

00:18:19.636 desirable, and talked a little bit about

00:18:22.292 types for systems programming.

 

00:18:23.910 In the remainder of this lecture,

00:18:25.798 I'll start by introducing the Rust programming

00:18:28.001 language as an example of a statically

00:18:30.204 typed, strongly typed language, which I believe

00:18:32.407 is suitable for systems programs.

Part 2: Introducing Rust: Basics Operations and Types

The 2nd 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.000 In this second part, I want to

00:00:03.195 start to Introduce the Rust programming language,

00:00:05.391 with a focus on basic types and

00:00:07.586 operations.

 

00:00:09.000 The Rust programming language is a modern

00:00:12.096 systems programming language.

00:00:13.424 It was initially developed by Graydon Hoare

00:00:16.620 as a side project, starting in 2006,

00:00:19.716 and development was sponsored by Mozilla for

00:00:22.813 over ten years starting in 2009.

00:00:25.467 The 1.0 release of the language was

00:00:28.664 made in 2015. And in December 2018,

00:00:31.760 a cleaned-up but backwards compatible version,

00:00:34.414 the Rust 2018 Edition, was released.

00:00:37.068 Since then, Rust has released new versions

00:00:40.265 every six weeks, maintaining a strong policy

00:00:43.361 of ensuring backwards compatibility while adding new

00:00:46.458 features.

 

00:00:48.000 The Rust version of the “Hello,

00:00:50.539 world!” program is shown on the slide.

00:00:53.502 As with many other languages, execution starts

00:00:56.564 with the main function.

00:00:58.257 Functions are defined with the fn keyword,

00:01:01.320 followed by the function name, its arguments

00:01:04.282 within parenthesis, and any return type.

00:01:06.821 The main() function in the example takes

00:01:09.784 no arguments and returns nothing.

 

00:01:12.000 The body of the function follows,

00:01:14.711 enclosed in braces.

00:01:16.066 In this case, the body comprises a

00:01:19.329 macro, println!(), that’s expanded at compile time.

00:01:22.491 Macro invocations in Rust always end with

00:01:25.654 an exclamation point, to distinguish them from

00:01:28.816 function calls. Macros in Rust are a

00:01:31.979 more sophisticated, and type safe, version of

00:01:35.141 the #define feature in C.

 

00:01:38.500 This slide shows a slightly more sophisticated

00:01:41.456 example.

00:01:42.628 The first line is a use statement,

00:01:45.683 that imports a library module. In this

00:01:48.639 case, the module env, that provides command

00:01:51.594 line argument parsing, is imported from the

00:01:54.550 standard library.

00:01:55.394 A use statement brings the public functions,

00:01:58.450 types, and other definitions of the imported

00:02:01.406 module into scope. Those functions can then

00:02:04.361 be referenced by name, relative to the

00:02:07.317 imported path, much like imports in Python.

00:02:10.272 For examples, this code call the env::args()

00:02:13.228 function.

 

00:02:13.000 The main() function in this example shows

00:02:15.914 a for loop in operation. The env::args()

00:02:18.828 function returns an iterator that returns the

00:02:21.742 command line arguments one-by-one, and the for

00:02:24.656 loop consumes the values generated by that

00:02:27.570 iterator, executing the body for each in

00:02:30.484 turn.

 

00:02:31.000 The println!() macro takes format strings to

00:02:33.554 specify how values are printed. This works

00:02:36.109 a lot like the format string in

00:02:38.663 a C printf() statement, except that the

00:02:41.218 format specifiers are surrounded by braces rather

00:02:43.772 than preceded by a % sign.

00:02:45.961 As we see from the bottom of

00:02:48.616 the slide, this program prints its command

00:02:51.170 line arguments

 

00:02:53.000 This third example is more sophisticated still.

00:02:56.115 Looking at the main() function, we see

00:02:59.330 that variables are defined in let bindings,

00:03:02.445 such as “let m = 12”.

00:03:05.115 This defines a new variable, m,

00:03:07.785 and binds the value to that variable.

 

00:03:11.000 The type of the variable is inferred

00:03:13.807 from the context. If the compiler can’t

00:03:16.613 infer the type, it can be specified

00:03:19.420 by following the variable name with a

00:03:22.227 colon, then the type name, before the

00:03:25.034 assignment of the value.

00:03:26.637 By default variable bindings are immutable.

00:03:29.143 That is, the value of the variables

00:03:31.950 m, n, and r in this function

00:03:34.757 cannot be changed after they have been

00:03:37.563 bound.

00:03:38.714 To make a mutable binding, that is

00:03:41.621 a variable whose value can change,

00:03:44.027 add the “mut” qualifier following the let

00:03:46.834 statement. For example, one could write “let

00:03:49.640 mut m = 12” to make m

00:03:52.447 a mutable variable.

 

00:03:53.000 Finally in main(), we see a call

00:03:55.891 to the gcd() function, to calculate the

00:03:58.782 greatest common divisor of m and n.

00:04:01.673 The gcd() function is defined first in

00:04:04.664 the code. We see that it takes

00:04:07.555 two parameters, m and n. Each of

00:04:10.445 these is mutable, that is, it can

00:04:13.336 be changed within the body of the

00:04:16.227 function, and is of type u64,

00:04:18.705 a 64 bit unsigned integer. The return

00:04:21.596 type of the function is also a

00:04:24.487 u64.

 

00:04:25.000 You’ll see that Rust requires the types

00:04:27.683 of the function arguments, and the return

00:04:30.367 type if the function returns a value,

00:04:33.050 to be explicitly stated. While it would

00:04:35.733 often be possible for the compiler to

00:04:38.417 infer the types of function arguments and

00:04:41.100 return value, the designers of Rust decided

00:04:43.783 they must always be explicitly stated to

00:04:46.467 avoid confusion, and provide documentation.

00:04:48.383 Within the function body, we see use

00:04:51.167 of the assert() macro, and if and

00:04:53.850 while statements. These all function in the

00:04:56.533 conventional way. The let binding within the

00:04:59.217 if statement creates a local variable binding.

 

00:05:02.000 You may notice one unusual feature of

00:05:04.950 the function: there is no return statement.

 

00:05:08.000 Rust distinguishes between statements and expressions.

00:05:10.693 Expressions evaluate to some value; statements have

00:05:13.834 no value. Statements end in semicolons,

00:05:16.527 expressions do not.

00:05:17.873 The gcd() function ends with an expression:

00:05:21.115 n. Like all expressions, it has a

00:05:24.256 value. And, since this value is the

00:05:27.398 last thing in the function, it is

00:05:30.539 returned. This is known as an implicit

00:05:33.680 return, and is a common idiom in

00:05:36.822 Rust. An explicit return, in the form

00:05:39.963 of a return statement, like in other

00:05:43.105 languages, is also possible.

 

00:05:45.000 Take a copy of the code on

00:05:47.709 the slide. Change the expression at the

00:05:50.419 end of the gcd() function, the line

00:05:53.128 with just n on its own,

00:05:55.450 into a statement by adding a semicolon

00:05:58.159 to the end, and compile the result.

00:06:00.869 Make sure you understand the error message

00:06:03.578 that results, and why it occurs.

 

00:06:07.000 We’ve seen some of the primitive types

00:06:09.948 available in Rust already. The available types

00:06:12.897 are very similar to those available in

00:06:15.845 C, although the type names are different.

00:06:18.794 The table shows the correspondence.

 

00:06:21.000 Aside from the names, there are two

00:06:23.772 major differences.

00:06:24.564 The first is that Rust has a

00:06:27.436 native bool type to hold a boolean

00:06:30.208 value, true or false. C does not

00:06:32.980 have a boolean type, and uses integers

00:06:35.752 to represent booleans, with a zero value

00:06:38.524 representing false, and non-zero representing true.

 

00:06:41.000 The second is the character type.

00:06:43.282 In C, a char is defined to

00:06:45.945 be one byte in size. The number

00:06:48.608 of bits in that byte, and whether

00:06:51.271 it is signed or unsigned are implementation

00:06:53.933 dependent, and the character set is not

00:06:56.596 specified. This makes it difficult to write

00:06:59.259 portable text handling code in C.

00:07:01.541 Rust, on the other hand, defines a

00:07:04.304 char to be a 32-bit Unicode scalar

00:07:06.967 value. This is entirely unambiguous in terms

00:07:09.629 of both the size of the character,

00:07:12.292 and the character set used. This makes

00:07:14.955 it much easier to write portable,

00:07:17.237 and internationalised, text handling code in Rust.

 

00:07:20.000 Note, though, that while Rust is better

00:07:22.920 than C here, Unicode is still very

00:07:25.841 complicated.

00:07:27.008 In particular, when dealing with text,

00:07:29.611 it’s often necessary to distinguish between the

00:07:32.532 Unicode concepts of scalar values, as used

00:07:35.452 in Rust; code points; grapheme clusters;

00:07:37.955 and characters. It makes sense for Rust

00:07:40.876 to use scalar values for its char

00:07:43.796 type, since these are the basic component

00:07:46.717 of Unicode. But, many things that people

00:07:49.637 recognise as characters, including emoji, are actually

00:07:52.558 Unicode grapheme clusters, represented as sequences of

00:07:55.478 scalar values, and cannot be encoded as

00:07:58.398 a single char.

 

00:07:59.000 If you want to process text character

00:08:01.745 by character, you probably want to use

00:08:04.489 libraries, such as the Unicode segmentation library

00:08:07.234 mentioned on the slide, that let you

00:08:09.979 work with grapheme clusters, rather than using

00:08:12.724 char values directly.

 

00:08:15.000 In addition to the primitive types,

00:08:17.370 Rust supports the usual set of compound

00:08:20.135 data types.

00:08:20.925 Arrays work as you might expect.

00:08:23.395 They hold a fixed number of elements,

00:08:26.160 all of the same type. Array bounds

00:08:28.925 are checked at run time.

 

00:08:32.000 In cases where you need a variable

00:08:34.543 length list, Rust provides a Vector,

00:08:36.723 Vec, type as part of the standard

00:08:39.267 library.

00:08:40.380 The Vec types follows a common pattern,

00:08:43.023 exposing a new() method that creates a

00:08:45.567 new instance of that type, as we

00:08:48.110 see in the example at the top

00:08:50.653 of the slide.

00:08:51.743 What’s notable here is that Vec takes

00:08:54.387 a type parameter, T, that indicates the

00:08:56.930 type of elements it will hold.

00:08:59.110 This parameter has to be specified when

00:09:01.653 creating an empty vector. We see two

00:09:04.197 ways of doing this.

 

00:09:05.000 The first is to call Vec::new() without

00:09:08.227 specifying the type parameter, but to assign

00:09:11.454 to a variable where the type is

00:09:14.680 specified. The example here specifies that the

00:09:17.907 variable, v, has type Vec, and the

00:09:21.134 new vector is assigned to that.

 

00:09:24.000 The second way is to explicitly include

00:09:29.862 the type parameter when creating the vector,

00:09:35.725 calling Vec::::new().

 

00:09:37.500 There’s also a convenience macro, that we

00:09:40.323 see at the bottom left, that creates

00:09:43.147 a vector from an array literal.

00:09:45.567 Internally, vectors are implemented as the equivalent

00:09:48.490 of a C program that uses malloc()

00:09:51.313 to allocate space for an array,

00:09:53.733 then realloc() to grow the space when

00:09:56.557 it becomes full. As a consequence of

00:09:59.380 this. conversion from a vector to an

00:10:02.203 array is extremely fast. The vector type

00:10:05.027 implements the Deref trait that provides such

00:10:07.850 a conversion to arrays, allowing vectors to

00:10:10.673 be passed to functions that expect array

00:10:13.497 types.

 

00:10:15.000 Rust supports tuples, that are collections of

00:10:17.837 unnamed values where each element can be

00:10:20.675 a different type.

00:10:21.891 In this example, the first and last

00:10:24.829 elements of the variable tup are integer

00:10:27.666 values, while the middle element is a

00:10:30.504 floating point value.

00:10:31.720 Elements of a tuple can be accessed

00:10:34.657 by index, starting at zero, using dot

00:10:37.495 notation.

 

00:10:38.000 Tuples can also be de-structured in a

00:10:40.318 let binding, as we see in the

00:10:42.636 second line of the function on the

00:10:44.953 slide, where the variables x, y,

00:10:46.940 and z are set to the elements

00:10:49.258 of the tuple. This behaviour is similar

00:10:51.576 to that of Python.

 

00:10:53.000 Rust also permits empty tuple values,

00:10:55.462 as we see at the bottom of

00:10:58.334 the slide. These represent the absence of

00:11:01.207 a value, much like the void type

00:11:04.079 in C.

 

00:11:06.000 Rust also supports structure types, that are

00:11:08.765 collections of named values, where each element

00:11:11.530 can have a different type.

00:11:13.505 Elements of a struct are accessed using

00:11:16.370 dot notation, as in other languages.

00:11:18.740 Instances of structs are created as we

00:11:21.605 see in the main() function, by specifying

00:11:24.370 the name of the struct, followed by

00:11:27.135 the values for its fields in braces.

 

00:11:31.000 It’s also possible to specify structs with

00:11:33.800 unnamed fields. These are known as tuple

00:11:36.600 structs. Values of a tuple struct can

00:11:39.400 be accessed in the same way as

00:11:42.200 values of a tuple, and instances of

00:11:45.000 a tuple struct are created by specifying

00:11:47.800 the struct name followed by the values

00:11:50.600 of its fields in parenthesis.

00:11:52.600 Tuple structs can be useful as type

00:11:55.500 aliases.

 

00:11:56.000 A struct can also be defined that

00:11:59.180 has no elements. These are known as

00:12:02.360 unit-like structs. Since they has no content,

00:12:05.540 unit-like structs takes up no space.

00:12:08.266 They’re useful as marker types or type

00:12:11.446 parameters.

 

00:12:12.000 We’ll discuss uses of tuple structs and

00:12:15.715 unit-like structs more in lecture 4.

 

00:12:20.000 Finally, it’s possible to implement methods on

00:12:22.800 a struct.

00:12:23.600 This is done by writing an impl

00:12:26.500 block, specifying the struct to be implemented,

00:12:29.300 as we see on the slide.

00:12:31.700 Method definitions take self as a parameter,

00:12:34.600 representing the struct on which they are

00:12:37.400 implemented. Access to fields of that struct

00:12:40.200 is via explicit self references, like in

00:12:43.000 Python.

00:12:44.150 Methods are called using the dot notation,

00:12:47.050 in the usual way.

 

00:12:48.000 A struct that implements methods looks a

00:12:50.914 lot like an object in Java or

00:12:53.828 Python. It’s different, though, in that Rust

00:12:56.742 does not support inheritance or subclassing.

00:12:59.240 Instead, it uses a feature known as

00:13:02.153 traits, that we’ll talk about in the

00:13:05.067 next part.

 

00:13:07.000 That concludes our introduction to the basic

00:13:09.709 operations and types provided by Rust.

00:13:12.030 At this level, Rust is a conventional

00:13:14.739 language, that offers few surprises.

00:13:16.674 In the next part, we’ll move on

00:13:19.483 to discuss traits, enumerations, and pattern matching,

00:13:22.191 that give Rust some more sophisticated behaviours.

Part 3: Introducing Rust: Traits and Enumerated Types

The 3rd 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.000 In this part, I’ll move on to

00:00:03.765 discuss some more advanced features of Rust,

00:00:06.530 including traits, enumerations, and pattern matching.

 

00:00:10.000 Traits are one of the primary ways

00:00:12.567 in which Rust introduces abstraction. They allow

00:00:15.133 you to define a set of operations

00:00:17.700 that can be performed on a type,

00:00:20.267 and to write code that works with

00:00:22.833 any type that implements those operations.

00:00:25.033 A trait defines a set of methods

00:00:27.700 and types. Those methods and types must

00:00:30.267 be implemented by any type that implements

00:00:32.833 that trait.

00:00:33.567 In the code sample on the slide,

00:00:36.233 for example, we see the definition of

00:00:38.800 trait Area. This trait includes the signature

00:00:41.367 of a single method, area(), that takes

00:00:43.933 self as a parameter and return a

00:00:46.500 value of type u32. The body of

00:00:49.067 the method is not specified.

 

00:00:51.000 The code then defines a struct,

00:00:53.303 Rectangle, with width and height, then implements

00:00:55.990 the trait Area for that struct.

00:00:58.294 The syntax “impl Area for Rectangle” specifies

00:01:01.081 that the Rectangle struct has an implementation

00:01:03.768 of the Area trait, and the body

00:01:06.455 of the impl block contains a definition

00:01:09.142 of the area() method, matching the signature

00:01:11.829 of the method given in the trait

00:01:14.516 definition.

 

00:01:15.000 Trait definitions usually just include method signatures,

00:01:17.975 as shown here, but they may also

00:01:20.950 include complete method implementations. Methods that have

00:01:23.925 their complete implementation specified in the trait

00:01:26.900 definition do not need to be written

00:01:29.875 in the impl block, but the impl

00:01:32.850 block needs to be present to indicate

00:01:35.825 that the type implements the trait.

00:01:38.375 Traits define functionality. Trait definitions cannot contain

00:01:41.450 instance variables or data; they just specify

00:01:44.425 methods.

00:01:45.600 At this level, traits behave like interfaces

00:01:48.675 in Java, or type classes in Haskell.

 

00:01:52.000 A trait can be implemented by multiple

00:01:54.800 types.

00:01:55.950 In this example, we show how we

00:01:58.850 can also define a struct Circle,

00:02:01.250 and implement the Area trait for that

00:02:04.050 type too.

00:02:04.850 Both Rectangle and Circle implement the Area

00:02:07.750 trait, and so include an area() method

00:02:10.550 with the same signature. The body of

00:02:13.350 the two methods differs, though.

00:02:15.350 Traits are an important tool for abstraction.

00:02:18.250 They allow you to describe common sets

00:02:21.050 of functionality that can be implemented by

00:02:23.850 different types.

 

00:02:25.000 Rust is not an object oriented language,

00:02:27.390 and you cannot inherit from a type,

00:02:29.779 or write code that works with subclasses

00:02:32.169 of a particular type. What you can

00:02:34.559 do, though, is write code that works

00:02:36.948 with any type that implements a particular

00:02:39.338 trait.

00:02:40.429 The slide shows the definition of a

00:02:42.919 trait, Summary, that include a single method,

00:02:45.309 summarise().

 

00:02:45.000 This is followed by definition of a

00:02:48.319 function, notify().

00:02:49.267 The notify() function takes a single parameter,

00:02:52.685 item, of type T. The type,

00:02:55.530 T, is a type parameter.

 

00:02:58.000 Type parameters are defined in angle brackets,

00:03:00.780 after a function’s name and before its

00:03:03.560 arguments. The definition here indicates that T

00:03:06.340 has type Summary. That is, T is

00:03:09.120 any type that implements the Summary trait.

 

00:03:12.000 Since all that is known about T

00:03:14.496 is that it implements the Summary trait,

00:03:16.992 the only legal operations on the variable,

00:03:19.489 item, with type T, are those defined

00:03:21.985 on that trait. As we see in

00:03:24.481 the println!() macro, we can call the

00:03:26.977 summarise() method on item, but we can

00:03:29.474 perform no other operations.

 

00:03:31.000 This approach lets us write generic code.

00:03:34.008 The function, notify(), doesn’t know or care

00:03:37.016 what is the actual type of T,

00:03:40.024 and whether it implements other traits,

00:03:42.603 methods, or instance variables, provided it implements

00:03:45.611 the Summary trait.

 

00:03:48.000 A number of traits are very widely

00:03:50.749 implemented.

00:03:51.892 For example, the standard library includes the

00:03:54.742 Debug trait that formats a value for

00:03:57.491 printing by a debugger. This is implemented

00:04:00.240 by all the primitive types, and by

00:04:02.990 most other types in the standard library.

00:04:05.739 The Rust compiler understands an annotation,

00:04:08.196 derive, written as shown in the code

00:04:10.945 sample on the slide.

00:04:12.516 The derive annotation can be added to

00:04:15.366 a struct definition, and tells the compiler

00:04:18.115 to generate a standard implementation for the

00:04:20.864 derived type.

 

00:04:21.000 For example, by writing #[derive(Debug)] on struct

00:04:24.114 Rectangle, as shown, we tell the compiler

00:04:27.228 to auto-generate an "impl Debug for Rectangle"

00:04:30.341 block.

00:04:31.536 This is possible, because every implementation of

00:04:34.750 the Debug trait proceeds in exactly the

00:04:37.864 same way. The code for the impl

00:04:40.978 block can be generated in an entirely

00:04:44.091 mechanical way, and always has the same

00:04:47.205 structure.

 

00:04:47.000 The first link on the slide points

00:04:50.133 to the list of derivable traits.

00:04:52.819 The second points to a description of

00:04:56.052 how to implement auto-derivation for a trait

00:04:59.186 you might define. While possible, it’s extremely

00:05:02.319 rare to implement auto-derivation for types you

00:05:05.452 define.

 

00:05:06.000 Using the #[derive()] annotation, though, is extremely

00:05:08.717 common. This can be used to derive

00:05:11.434 standard traits such as Debug so the

00:05:14.151 object can be printed by a debugger;

00:05:16.868 to implement equality tests for structures,

00:05:19.197 by deriving an implementation of the Eq

00:05:21.914 trait; and to allow copies to be

00:05:24.631 made of objects by deriving the Copy

00:05:27.347 trait, and so on.

 

00:05:30.000 Finally, traits can include definitions of associated

00:05:33.087 types. That is, that can specify that

00:05:36.175 certain types must be specified when the

00:05:39.262 trait is implemented.

00:05:40.586 For example, for loops in Rust operate

00:05:43.773 on iterators, where an iterator is defined

00:05:46.861 to be something that implements the Iterator

00:05:49.948 trait.

00:05:51.139 The Iterator trait defines a method and

00:05:54.327 an associated type.

 

00:05:55.000 The method is called next(). It returns

00:05:57.544 the next element in the sequence produced

00:06:00.088 by the iterator, or an indication that

00:06:02.632 there are no more elements. This is

00:06:05.176 an instance of an enum type,

00:06:07.356 Option, that we’ll discuss in a minute.

 

00:06:10.000 The Option includes a type parameter,

00:06:13.270 Self::Item. This references the other element of

00:06:17.085 the trait definition, a type called Item.

 

00:06:21.000 What is the Item type? The trait

00:06:23.862 definition doesn’t specify. It indicates that all

00:06:26.724 implementations of the trait need to define

00:06:29.585 the Item type, but otherwise puts no

00:06:32.447 constraint on what it may be.

 

00:06:35.000 Every Implementation of the Iterator trait must

00:06:38.132 include a line, type Item = something,

00:06:41.265 to specify that type, and must define

00:06:44.397 the next() function to return an optional

00:06:47.530 value of that type. The trait is

00:06:50.662 generic, over any possible type.

 

00:06:54.000 Traits allow you to write code that

00:06:56.502 operates on many different types, by abstracting

00:06:59.004 away the operations that need to be

00:07:01.506 performed on those types.

00:07:02.936 Enumerated types, enums, allow you to write

00:07:05.538 code that can access the value of

00:07:08.040 data that may be of several different

00:07:10.543 types.

 

00:07:11.000 In the simplest case, enums work the

00:07:13.826 same way they do in C or

00:07:16.652 Java. They specify a set of named

00:07:19.478 values that an item may take.

 

00:07:22.000 Rust also allows two more general forms

00:07:24.702 of enum, though.

00:07:25.859 The first is an enum that can

00:07:28.661 hold unnamed data items, like a tuple

00:07:31.363 struct that can take several different variants.

00:07:34.064 In this example, the RoughTime enum can

00:07:36.866 hold values indicating JustNow, InThePast, or InTheFuture.

00:07:39.567 If the value is in the past

00:07:42.269 or future, the enum also holds a

00:07:44.970 time unit and a count.

 

00:07:47.000 For example, the variable “when” in the

00:07:50.666 code fragment indicates something that happened four

00:07:54.332 score and seven years ago. The InThePast

00:07:57.997 variant of the enum takes two unnamed

00:08:01.663 parameters, a TimeUnit and a number,

00:08:04.805 four score and seven.

 

00:08:07.000 An enum can also hold named data,

00:08:09.673 acting like a struct that can take

00:08:12.345 several different variants.

00:08:13.491 In this example, the enum Shape,

00:08:15.882 can be either a Sphere, with a

00:08:18.555 centre and a radius, or a Cuboid

00:08:21.227 specified by the locations of two corners.

 

00:08:25.000 An enum is used when a variable,

00:08:27.674 parameter, or result can have on of

00:08:30.349 several possible types. Enums define the set

00:08:33.023 of possible alternative types for a type,

00:08:35.697 and are used to model data that

00:08:38.372 can take one of a set of

00:08:41.046 related values.

00:08:41.810 Like structs, enums can have type parameters

00:08:44.585 that must be specified when the enum

00:08:47.259 is instantiated. For example, the Rust standard

00:08:49.933 library defines an enum Result, that takes

00:08:52.608 two type parameters, T and E.

 

00:08:55.000 There are two variants to the Result

00:08:58.033 enum. The Ok(T) variant is used to

00:09:01.067 indicate a successful result, wrapping a value

00:09:04.100 of type T. The Err(E) variant is

00:09:07.133 used to indicate an error, wrapping a

00:09:10.167 result of type E.

 

00:09:12.000 Enums can also have impl blocks that

00:09:14.832 define methods that can be invoked on

00:09:17.664 the enum, and they can themselves implement

00:09:20.495 traits.

 

00:09:22.000 The Rust standard library defines two extremely

00:09:24.680 useful standard enum types.

00:09:26.211 One is the Result type, that we

00:09:28.991 saw previously, that’s returned by functions that

00:09:31.671 may either succeed or fail. For example,

00:09:34.351 at the bottom of the slide we

00:09:37.031 see the definition of a recv() function,

00:09:39.711 that returns a Result that can be

00:09:42.391 either Ok, wrapping a value of type

00:09:45.071 Message, or an Err variant that wraps

00:09:47.751 a NetworkError object.

 

00:09:49.000 The other is the Option type.

00:09:51.034 This represents a value that might not

00:09:53.407 exist.

00:09:54.496 In a C program, for example,

00:09:56.630 one might write a function to lookup

00:09:59.004 a key in a database. This function

00:10:01.377 might take a pointer to the struct

00:10:03.750 representing the database, and a pointer to

00:10:06.123 the key to be found. If the

00:10:08.496 key is found in the database,

00:10:10.530 such a function will return a pointer

00:10:12.904 to the corresponding value, or it will

00:10:15.277 return null if they key doesn’t exist.

 

00:10:17.000 A Java program would be similar,

00:10:18.980 except that lookup() would be a method

00:10:21.290 on the database object, and would return

00:10:23.600 a reference to an object holding the

00:10:25.910 value, or null.

 

00:10:27.000 In Rust, the equivalent function would return

00:10:30.022 an instance of the Option type.

00:10:32.612 Option is an enum, that takes a

00:10:35.633 type parameter T, and has two possible

00:10:38.655 variants. Some(T) indicates that the item is

00:10:41.677 present, and None indicates that it is

00:10:44.698 not. The Rust function would therefore return

00:10:47.720 an Option, with the variant indicating whether

00:10:50.742 the result exists or not.

 

00:10:53.000 This looks like a minor syntactic difference,

00:10:55.396 but as we’ll see later in the

00:10:57.792 lecture, it lets the Rust compiler check

00:11:00.188 for errors much more effectively.

 

00:11:03.000 The final Rust feature I want to

00:11:05.809 discuss in this part of the lecture

00:11:08.619 is pattern matching.

00:11:09.823 Pattern matching introduces the match statement.

00:11:12.331 This is a generalisation of the switch

00:11:15.141 statement in languages like C and Java.

00:11:17.950 In the simplest case, much like in

00:11:20.859 C, a match statement can match on

00:11:23.669 an integer value. In this example,

00:11:26.077 the count_rabbits() method is called on the

00:11:28.886 meadow object, and the match statement operates

00:11:31.696 on the result.

 

00:11:33.000 If there are no rabbits, nothing is

00:11:35.441 printed. If there is one rabbit,

00:11:37.532 it prints that a rabbit is nosing

00:11:39.973 around. And if there are several rabbits,

00:11:42.414 it prints to say how many rabbits

00:11:44.854 are hopping about.

 

00:11:46.000 The last variant shows the first extension

00:11:48.319 of the Rust match statement compared to

00:11:50.638 the C switch statement. A match can

00:11:52.956 include a variable that’s bound if none

00:11:55.275 of the other variants match, and that

00:11:57.594 variable can be used when that branch

00:11:59.913 of the switch statement is executed.

 

00:12:02.000 A wildcard that doesn’t bind to a

00:12:04.762 value can be specified using an underscore

00:12:07.524 as the value to match.

00:12:09.496 Match statements in Rust are exhaustive.

00:12:11.964 That is, every possible value must match,

00:12:14.725 or there must be a wildcard or

00:12:17.487 variable match.

00:12:18.276 It’s a compile time error if some

00:12:21.138 values are not covered by the match.

 

00:12:25.000 Rust also generalises the match statement to

00:12:27.699 allow matching on other types, not just

00:12:30.398 integers. The slide shows a match against

00:12:33.097 string values, for example, that evaluate to

00:12:35.796 an enum variant.

00:12:36.952 A match statement in Rust has a

00:12:39.751 value that’s equal to that of the

00:12:42.450 chosen branch. This means it’s possible to

00:12:45.149 use a match statement to assign a

00:12:47.848 value to a variable in a let

00:12:50.547 binding, as shown in the slide.

00:12:52.860 All variants of a match statement must

00:12:55.659 evaluate to give values of the same

00:12:58.358 type, or to nothing.

 

00:13:01.000 Match statements in Rust can also match

00:13:03.621 against enum variants.

00:13:04.744 On this slide we have the same

00:13:07.465 RoughTime example as used before, with a

00:13:10.085 match statement that checks which variant of

00:13:12.706 the enum is present, and produces a

00:13:15.327 different value in each case.

00:13:17.199 This allows code to be written that

00:13:19.920 can deal with data that can be

00:13:22.540 one of several different variants, one of

00:13:25.161 several different types. Since matches are exhaustive,

00:13:27.782 the compiler will guarantee that all code

00:13:30.402 handles all possible variants.

 

00:13:33.000 This is extremely useful for writing code

00:13:35.725 that handles optional values and results that

00:13:38.450 may fail.

00:13:39.229 For example, in C one might write

00:13:42.054 a function that looks up a user

00:13:44.779 in a database then books a ticket

00:13:47.504 for that user. The get_user() function returns

00:13:50.229 a pointer to the customer record on

00:13:52.954 success, or null on failure.

 

00:13:55.000 It’s easy to write code, as shown

00:13:57.656 on the slide, that assumes the get_user()

00:14:00.312 function succeeds and always tried to book

00:14:02.968 the ticket, causing the book_ticket() function to

00:14:05.624 crash when passed a null pointer.

 

00:14:08.000 C cannot catch the bug at compile

00:14:12.288 time.

 

00:14:13.000 In Rust, though, the get_user() function will

00:14:15.487 return an instance of the Option enum,

00:14:17.975 and the code will eventually have to

00:14:20.462 pattern match against this to get at

00:14:22.950 the result. The pattern match must be

00:14:25.437 exhaustive, which means that the code won’t

00:14:27.925 compile unless both the Some() and None

00:14:30.412 variants of the Option type are handled.

 

00:14:33.000 The Rust compiler can’t make you write

00:14:35.800 meaningful error handling, for cases where the

00:14:38.600 get_user() function fails, but it does force

00:14:41.400 you to check for and handle the

00:14:44.200 error somehow, and the code won’t compile

00:14:47.000 if you forget the error handling.

00:14:49.400 Rust therefore turns a runtime failure into

00:14:52.300 a compile time check.

 

00:14:55.000 In this part, I’ve introduced the concepts

00:14:57.826 of traits and enums, that provide abstraction

00:15:00.652 in Rust, and the idea of pattern

00:15:03.478 matching for working with variant data.

 

00:15:06.000 We’re also now starting to see how

00:15:08.689 the type system can help us write

00:15:11.379 reliable and robust software. The Option and

00:15:14.068 Result enums are small types in themselves,

00:15:16.758 but when used systematically, in combination with

00:15:19.447 exhaustive pattern matching, they remove a common

00:15:22.137 source of bugs: forgetting to check for

00:15:24.826 failures in the return value of function

00:15:27.516 calls.

 

00:15:28.000 In the next part, we’ll move on

00:15:31.450 to talk about how Rust handles pointers.

Part 4: Introducing Rust: References and Memory Allocation

The 4th part of the lecture concludes this 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. Finally, it talks about what makes Rust interesting as a systems language, and what is novel about its design.

00:00:00.000 In the final part of this lecture,

00:00:03.150 I’d like to start to discuss one

00:00:05.300 of the more unusual features of Rust:

00:00:07.450 how it handles memory management. I’ll also

00:00:09.600 say a little about why I think

00:00:11.750 Rust is an interesting systems programming language.

 

00:00:15.000 At a first glance, memory management in

00:00:18.033 Rust looks a little like it does

00:00:21.067 in C.

00:00:21.933 Like in C, the act of taking

00:00:25.067 a reference, a pointer, to an object

00:00:28.100 is explicit. And, similarly, so is dereferencing

00:00:31.133 a pointer to access the referenced object.

00:00:34.167 The slide shows how to create a

00:00:37.300 variable binding, let x = 10

 

00:00:40.000 And it demonstrates how to take a

00:00:42.557 reference to that binding, let r =

00:00:45.113 &x

00:00:46.228 In both cases, we see that Rust

00:00:48.885 infers the type of x and r,

00:00:51.441 whereas in the equivalent C code,

00:00:53.633 shown on the right, we have to

00:00:56.189 explicitly write the type.

 

00:00:57.000 And the terminology is different, with Rust

00:00:59.893 calling the variable r a reference to

00:01:02.787 x, whereas it would be called a

00:01:05.680 pointer to x in C. But otherwise,

00:01:08.573 the code is the same.

00:01:10.640 The same is true for dereferencing,

00:01:13.220 where we write let s = *r.

00:01:16.113 The * operator, used to dereference a

00:01:19.007 pointer, is the same in both languages.

 

00:01:22.000 Functions can take their parameters by reference.

00:01:24.638 For example, the calculate_length() function, shown on

00:01:27.276 the slide, is passed a reference to

00:01:29.914 a buffer, rather than passing the buffer

00:01:32.552 itself. This behaves the same as the

00:01:35.190 equivalent C code, that passes a pointer

00:01:37.828 to the buffer.

00:01:38.958 Rust is a little more consistent than

00:01:41.696 C here. It uses the & syntax

00:01:44.334 to both take a reference and to

00:01:46.972 pass a reference to a value,

00:01:49.233 while C uses the & syntax to

00:01:51.871 take a reference, but the * syntax

00:01:54.509 to pass a reference.

00:01:56.017 The compiler generates the exact same code

00:01:58.755 for the Rust and C programs,

00:02:01.016 in all of these cases.

 

00:02:04.000 One of the unusual features of Rust

00:02:07.130 is that is distinguishes two different types

00:02:10.260 of reference: immutable references and mutable references.

00:02:13.391 An immutable reference is written using an

00:02:16.621 ampersand, as in the code fragment at

00:02:19.751 the top: let r = &x

00:02:22.434 An immutable reference is a reference to

00:02:25.664 an object that cannot change.

 

00:02:28.000 The code fragment shown at the top

00:02:30.563 of the slide, that takes an immutable

00:02:33.126 reference to a variable, then tries to

00:02:35.689 change the referenced value, won’t compile.

00:02:37.886 The compiler notices that the reference is

00:02:40.449 immutable, and throws an error indicating that

00:02:43.012 it cannot assign to the referenced value.

00:02:45.575 A mutable reference is written using the

00:02:48.238 syntax &mut as we see in the

00:02:50.802 second code fragment.

 

00:02:52.000 It allows the referenced value to change.

00:02:54.686 And, if you compile and run the

00:02:57.371 code, you’ll see that it prints the

00:03:00.057 value 15, after having successfully changed the

00:03:02.743 value of x via the reference.

00:03:05.045 The two different types of reference constrain

00:03:07.831 what can be done with the referenced

00:03:10.516 value.

 

00:03:12.000 In addition to distinguishing between mutable and

00:03:15.013 immutable references, Rust enforces a number of

00:03:18.026 constraints on how references can be created

00:03:21.039 and used.

 

00:03:22.000 The first is that references in Rust

00:03:24.595 can never be null. They always point

00:03:27.190 to a valid object.

00:03:28.673 It is not possible to create or

00:03:31.368 return a null pointer in Rust.

00:03:33.592 Values that would be a potentially null

00:03:36.287 pointer in C or Java are handled

00:03:38.882 by returning an Option type. As we

00:03:41.477 saw in the previous part of the

00:03:44.072 lecture, this is an enum that either

00:03:46.667 has the value Some(x), where x is

00:03:49.262 the value, or has the value of

00:03:51.857 None. The option is extracted using pattern

00:03:54.452 matching, allowing the compiler to enforce the

00:03:57.046 check for the None case.

 

00:04:00.000 The second constraint is that while Rust

00:04:02.783 allows many immutable references to an object

00:04:05.566 to exist, it prohibits there from being

00:04:08.349 any mutable references to that object at

00:04:11.132 the same time.

00:04:12.324 And, while an immutable reference to an

00:04:15.207 object exists, the Rust compiler enforces that

00:04:17.990 the referenced object is immutable, even if

00:04:20.773 that object was declared to be mutable.

00:04:23.556 You can be sure that, while an

00:04:26.439 immutable reference to an object exists,

00:04:28.824 that object will not change.

00:04:30.812 The compiler enforces this constraint.

 

00:04:34.000 Further, the compiler enforces that there can

00:04:36.971 be at most one mutable reference to

00:04:39.943 an object in scope. And that there

00:04:42.914 can be no immutable references to the

00:04:45.886 object while the mutable reference exists.

00:04:48.433 The compiler also enforces that the original

00:04:51.504 object is inaccessible while the mutable reference

00:04:54.476 exists.

 

00:04:55.000 If you have a mutable reference to

00:04:57.119 an object, you can read or modify

00:04:59.239 that object via the reference, and you

00:05:01.358 can be sure that no other part

00:05:03.478 of the program has access to that

00:05:05.597 object.

 

00:05:07.000 The compiler strictly enforces these guarantees.

00:05:09.855 They limit what types of program you

00:05:13.285 can write, by enforcing constraints on what

00:05:16.616 references to data can exist at different

00:05:19.947 times.

00:05:21.173 As a consequence though, these rules make

00:05:24.603 null pointer exceptions, iterator invalidation, and data

00:05:27.934 races between threads impossible in Rust.

00:05:30.789 They trade off flexibility for safety.

00:05:33.744 We’ll talk more about this in Lecture

00:05:37.174 5.

 

00:05:38.000 It addition to allowing references to existing

00:05:40.922 objects, Rust makes it possible to allocate

00:05:43.843 memory on the heap.

00:05:45.513 In C, memory on the heap is

00:05:48.535 allocated using the malloc() function. This takes

00:05:51.457 as its argument the size of the

00:05:54.378 required allocation, and returns a pointer to

00:05:57.300 uninitialised heap memory of the appropriate size.

00:06:00.222 A value can then be stored in

00:06:03.143 the allocated memory, by writing to the

00:06:06.065 dereferenced pointer.

 

00:06:07.000 We see this in the code highlighted

00:06:09.751 in blue on the slide, where the

00:06:12.502 malloc() call allocates space for an integer,

00:06:15.253 and assigns this to the pointer b.

00:06:18.005 Then, in the next statement, the code

00:06:20.756 write the value 5 to the allocated

00:06:23.507 space.

 

00:06:24.000 Rust uses a type known as Box

00:06:26.948 to refer to heap allocated memory.

00:06:29.476 The Box type is a smart pointer

00:06:32.424 type, that references an object of type

00:06:35.373 T that’s stored on the heap.

 

00:06:38.000 In the code on the left,

00:06:40.479 the statement let b = Box::new(5) creates

00:06:43.372 a new box. While the equivalent C

00:06:46.264 code allocates memory, then separately assigns a

00:06:49.157 value to that memory, the Box new()

00:06:52.049 function is given the value to be

00:06:54.942 stored, and allocates the memory and stores

00:06:57.834 the value in one call.

 

00:07:00.000 That is, when we write Box::new(5),

00:07:02.491 we are not saying “allocate 5 bytes

00:07:05.397 of memory”. Rather, we’re saying allocate enough

00:07:08.304 memory to hold an integer, and store

00:07:11.210 the integer value 5 into that memory.

00:07:14.116 The implementation of a box is as

00:07:17.123 a pointer to the heap allocated memory.

00:07:20.029 The variable, b, is represented in exactly

00:07:22.935 the same way in the Rust program

00:07:25.842 and in the C program. The difference

00:07:28.748 is in the way allocation is exposed

00:07:31.654 to the programmer.

 

00:07:33.000 Memory allocation in Rust is safer than

00:07:35.879 the equivalent in C, for three reasons.

00:07:38.758 Firstly, the value returned by Box::new() is

00:07:41.738 guaranteed to be initialised. There’s no way

00:07:44.617 to read from uninitialised memory in Rust,

00:07:47.496 whereas C allows you to read from

00:07:50.375 the allocated memory before making an assignment,

00:07:53.255 which gives undefined behaviour.

 

00:07:55.000 Second, the allocation is guaranteed to be

00:07:57.506 the correct size in Rust. The C

00:08:00.012 language makes no attempt to check that

00:08:02.518 the size of memory allocated by malloc()

00:08:05.024 matches the size of the object stored

00:08:07.530 in that memory, and has undefined behaviour

00:08:10.036 if the object is larger than the

00:08:12.542 allocation.

 

00:08:13.000 And, finally, Rust guarantees that the memory

00:08:15.813 will be automatically deallocated when the box

00:08:18.627 goes out of scope. In C,

00:08:21.038 it’s necessary to manually call the free()

00:08:23.852 function to deallocate memory, and it’s easy

00:08:26.665 to either forget to free memory,

00:08:29.077 wasting resources, or to free memory too

00:08:31.890 early, leading to undefined behaviour.

 

00:08:34.000 By default, a Box is Rust is

00:08:37.085 immutable and its contents cannot be changed.

00:08:40.170 A mutable box can be created,

00:08:42.815 that does allow the value to change.

 

00:08:46.000 Finally, boxes do not implement the standard

00:08:48.800 Copy trait. This means that you can

00:08:51.600 pass boxes around, but you cannot make

00:08:54.400 copies of them. It’s guaranteed that only

00:08:57.200 one copy of a box exists.

00:08:59.600 This is to prevent data races between

00:09:02.400 threads.

 

00:09:04.000 Strings in Rust are defined to be

00:09:07.243 Unicode text, and are encoded in UTF-8

00:09:10.486 format. This allows them to represent the

00:09:13.729 full range of international text.

00:09:16.045 Somewhat confusingly, there are two string types.

00:09:19.388 A str is an immutable string slice,

00:09:22.731 that’s always accessed via an immutable reference

00:09:25.973 as &str

 

00:09:27.000 String literals are of type &str

00:09:29.933 The &str type is built-in to the

00:09:33.456 language, as a primitive type.

 

00:09:37.000 A String is a mutable string buffer

00:09:40.015 type, implemented in the standard library.

00:09:42.600 A variable of type &str cannot change.

00:09:45.715 A String can be modified, as we

00:09:48.731 see on the slide, and can be

00:09:51.746 created from a string literal.

 

00:09:54.000 If you’re a Java programmer, a String

00:09:56.927 in Rust is equivalent to a StringBuffer

00:09:59.855 in Java. The &str type in Rust

00:10:02.782 is equivalent to a Java String.

00:10:05.291 The names in Rust are confusing.

 

00:10:09.000 Finally, the String type in Rust implements

00:10:12.459 the Deref trait from the standard library.

00:10:15.918 This allows the compiler to implement automatic

00:10:19.376 dereferencing for Strings.

00:10:20.859 In the example code, the variable s

00:10:24.418 has type String

 

00:10:26.000 If we write “let r = &s;”

00:10:29.300 then we get a reference to that

00:10:32.600 string. The variable r has type &string

 

00:10:36.000 If, instead, we take a reference to

00:10:38.784 s and assign it to the variable

00:10:41.569 t, that we’ve specified as being of

00:10:44.353 type &str, then the compiler uses the

00:10:47.138 implementation of the Deref trait to perform

00:10:49.922 the conversion, giving us an &str,

00:10:52.309 an immutable string slice.

 

00:10:54.000 This conversion has no runtime cost,

00:10:56.527 since it just involves taking a pointer

00:10:59.476 to the internal mutable buffer of the

00:11:02.424 String type. The usual Rust rules about

00:11:05.373 immutable references mean that the underlying string

00:11:08.321 becomes unchangeable while the &str reference exists.

00:11:11.270 Since this conversion is free, functions that

00:11:14.318 don’t need to mutate the string tend

00:11:17.267 to be only implemented for &str and

00:11:20.215 not on String values.

 

00:11:23.000 That concludes our initial review of the

00:11:26.302 Rust programming language.

00:11:27.717 As should be clear, Rust is largely

00:11:31.120 a traditional systems language. The basic types,

00:11:34.422 control flow, and data structures are very

00:11:37.724 familiar to programmers coming from other languages.

00:11:41.026 It makes some innovations, for a systems

00:11:44.428 language.

 

00:11:45.000 Enumerated types and pattern matching are well-known

00:11:48.475 features of functional programming languages, as are

00:11:51.950 the Option and Result types, but they’re

00:11:55.425 not previously been used in systems programming.

 

00:11:59.000 Similarly, the use of structures and traits

00:12:02.015 as an alternative to object oriented programming

00:12:05.031 mirrors the use of type classes in

00:12:08.046 Haskell, but is new in the systems

00:12:11.062 domain.

00:12:12.242 Overall, there’s relatively little in Rust that

00:12:15.358 is truly novel.

 

00:12:16.000 The syntax is a little different from

00:12:18.830 that of C, but where it differs

00:12:21.661 it mostly takes inspiration from Standard ML.

00:12:24.491 The basic data types closely match those

00:12:27.422 of C.

00:12:28.230 Enumerated types are pattern matching come from

00:12:31.161 Standard ML.

00:12:31.970 Traits are adopted from Haskell type classes.

 

00:12:35.000 And there are many influences from C++,

00:12:37.784 but these generally of the form of

00:12:40.569 looking at how C++ solves a problem,

00:12:43.353 and doing the opposite. Rust tends to

00:12:46.138 favour the safe default, while C++ tends

00:12:48.922 to prefer performance, and makes the safe

00:12:51.707 choice an option.

 

00:12:53.000 The one area where Rust is novel

00:12:55.902 is memory management. The ideas around references

00:12:58.804 and ownership, that we’ve touched on in

00:13:01.706 this lecture, and will talk more about

00:13:04.608 later in the course are unique to

00:13:07.510 Rust. Although, even here, they’re influenced by

00:13:10.412 previous work on the Cyclone language.

 

00:13:14.000 What makes Rust an interesting language?

00:13:16.566 Well, it employs a safe, modern type

00:13:19.659 system.

00:13:20.837 It has no concept of undefined behaviour.

00:13:23.930 And it’s memory safe. Rust programs don’t

00:13:27.024 suffer from undefined behaviour due to buffer

00:13:30.017 overflows, dangling pointers, or null pointer dereferences.

00:13:33.011 And the type system is expressive enough,

00:13:36.104 with enough zero cost abstractions, that it

00:13:39.097 can be used to model the problem

00:13:42.091 space and check designs for consistency -

00:13:45.084 as we’ll discuss in lecture 4.

 

00:13:48.000 Rust is interesting because it has a

00:13:50.749 type system that can model data and

00:13:53.497 resource ownership.

00:13:54.282 It provides deterministic automatic memory management,

00:13:56.738 that prevents iterator invalidation, use-after-free bugs,

00:13:59.094 and most memory leaks. And that lets

00:14:01.843 us model state machines, and resource use

00:14:04.591 in state machines, in a way that

00:14:07.340 makes it easier to validate system designs

00:14:10.088 for correctness.

00:14:10.874 We’ll talk more about this in lectures

00:14:13.722 5 and 6

 

00:14:15.000 And Rust has rules around references and

00:14:18.047 ownership prevent data races in concurrent code.

00:14:21.094 That enforce the design patterns that are

00:14:24.141 common in well-written C programs.

00:14:26.318 We’ll talk most about these in lecture

00:14:29.465 7.

 

00:14:31.000 And, fundamentally, Rust is a systems programming

00:14:34.220 language that eliminates many classes of bug

00:14:37.440 that are common in C and C++

00:14:40.660 programs.

00:14:41.870 It makes it easier to write correct

00:14:45.190 software.

 

00:14:46.000 That concludes this lecture.

00:14:47.529 I’ve discussed what is a strongly typed

00:14:50.305 language, hopefully shown you why it’s desirable.

00:14:52.981 And I’ve begun to introduce the Rust

00:14:55.656 language, which is one example of a

00:14:58.332 modern, strongly typed, systems language.

00:15:00.244 In the next lecture, I’ll move on

00:15:03.019 to discuss how we can use typing

00:15:05.695 to help model the problem domain,

00:15:07.989 to write more robust programs.

Discussion

The lecture focussed on the definition of a type system and of strongly typed languages, and introduced the Rust programming language.

Consider strong and weak types in the context of safe and unsafe languages. A safe language, whether static or dynamic, know 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.

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 and the labs focussed on Rust, a modern systems programming language with a strong static type system. Rust is a largely traditional systems programming language: the basic types, control flow, and data structures are very familiar. Its key innovations for a systems language are enumerated types and pattern matching, the use of structure types and traits as an alternative to object oriented programming, and the use of multiple reference types and ownership tracking for memory management.

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?