CDS 210: Fall 2026
Welcome to DS210!
This site holds the syllabus, schedule, lecture notes, and handouts for assignments and discussion sections.
Lectures meet Monday, Wednesday, and Friday in 871 Commonwealth Ave, CGS 505.
- Section A1: 11:15am - 12:05pm
- Section B1: 12:20pm - 1:10pm
Both sections cover the same material.
Discussion sections meet for 50 minutes. A sections (A2, A3, A4) meet Wednesday afternoons. B sections (B2, B3, B4) meet Tuesdays.
Where to find things
- Syllabus - policies, grading, and what the course covers
- Schedule - week by week, with due dates
- Lecture notes are in the sidebar, one page per lecture
- Projects, Discussions, and Activities will also be added as they are released
What this course is about
CDS 210 builds on CDS 110 by moving from Python to a systems language. You will learn how a computer actually stores and manages data, why that matters for the programs you write, and how Rust's approach to memory lets you write fast code without the crashes that come with managing memory by hand.
By the end, you will be able to take a slow piece of Python, rewrite the expensive part in Rust, and call it back from Python.
CDS 210 - Fall 2026 Syllabus
- Course description
- Teaching Staff
- Meeting Times and Rooms
- Office Hours and Coffee Chats
- Course Websites
- Course Content Overview
Overview
Course description
This course builds on DS110 (Python for Data Science) by expanding on programming language, systems, and algorithmic concepts introduced in the prior course. The course begins by exploring the different types of programming languages and introducing students to important systems-level concepts such as computer architecture, compilers, file systems, and using the command line. It then introduces a high-performance language (Rust), how it manages memory, and how to use it to implement fundamental data structures and algorithms. Then it covers how to use Rust in conjunction with Python and external libraries to perform data manipulation and analysis.
Prerequisites: CDS 110 or equivalent
BU Hub units: this course meets requirements for Quantitative Reasoning II, Creativity/Innovation, and Digital/Multimedia Expression. For details on how the course meets the learning outcomes for each, see the appendix.
Teaching Staff
Instructor (both sections): Lauren Wheelock
Email: laurenbw@bu.edu
Office: CDS 1506
| Teaching Assistants | Course Assistants |
|---|---|
| Matthew Morris mattmorr@bu.edu | Kesar Narayan kesar@bu.edu |
| Emir Tali etali@bu.edu | Lingjie Su sljleo@bu.edu |
| Kristen Bestavros kbest@bu.edu | |
| Gabriel Burr gsb@bu.edu | |
| Nivedhaa (Nia) Naresh Kumar nkmar@bu.edu |
Our TAs and CAs have all taken 210 themselves and are passionate about the subject and teaching it. They are a great resource, so lean on them when you need to!
For anything about the course, Piazza is usually faster than email and helps us track open loops, so please use it over email when possible.
See Office Hours and Coffee Chats below for when we are available.
Meeting Times and Rooms
Both lecture sections meet Mondays, Wednesdays, and Fridays in 871 Commonwealth Ave, CGS 505.
A1 Lecture: 11:15am-12:05pm
B1 Lecture: 12:20pm-1:10pm
Section A Discussions (Wednesdays, 50 min):
- A2: 1:25pm - 2:15pm, 871 Commonwealth Ave CGS 525 (led by Matt)
- A3: 2:30pm - 3:20pm, 871 Commonwealth Ave CGS 525 (led by Gabriel)
- A4: 3:35pm - 4:25pm, 871 Commonwealth Ave CGS 525 (led by Gabriel)
Section B Discussions (Tuesdays, 50 min):
- B2: 11:00am - 11:50am, 111 Cummington St MCS B31 (led by Emir)
- B3: 12:30pm - 1:20pm, 111 Cummington St MCS B31 (led by Kristen)
- B4: 2:00pm - 2:50pm, 665 Comm Ave CDS 164 (led by Nia)
Note: the official schedule lists the B discussion sections as running until 12:15pm, 1:45pm, and 3:15pm, because that is the full length of those time slots. We will typically only use 50 minutes, ending at the times listed above. On code review weeks, B3 and B4 may use the full time.
Note: You must attend the lecture and discussion sessions you are assigned to. We can make one-off exceptions with sufficient notice but, in general, showing up to a different lecture or section without notice will result in no attendance credit and may cause other issues (especially for code reviews and exam corrections).
Office Hours and Coffee Chats
Prof. Wheelock's office hours
Drop-in, no sign-up needed, in CDS 1506.
- Mondays 9:30 - 10:30am
- Wednesdays 9:30 - 10:30am
Come with a question, to work on the project near other people, or to listen to what others are asking. If you want to speak privately let me know in advance.
Staff office hours
All TA and CS office hours will be in the CDS building's 5th floor Pavillion:
- Mon 5-6: Kesar @ East Side
- Wed 4-5: Lingjie @ East Side
- Wed 5-6: Gabriel @ East Side
- Thu 4-5: Kristen @ South Side
- Thu 5-6: Matt @ East Side
- Fri 1:30-2:30: Nia @ West Side
- Fri 2:30-3:30: Emir @ East Side
Coffee chats with Prof. Wheelock
Coffee chats are 20 minute appointments you can book with me, individually or in small groups. There will literally be coffee (or new this semester - tea or hot chocolate). Coffee chats have one rule: we do not talk about the course. No discussion of grades, assignments, or the material. They are for talking about life, career plans, research, what you want to do after this, existential philosophy, whether AI is going to take over the world, or whatever is on your mind.
- Fridays 9:30 - 10:30am
- Every other Tuesday 2:00 - 3:00pm, starting September 8
Sign up at https://calendly.com/laurenbw-bu/coffee-chats. If nobody has signed up for a slot by that morning, it becomes drop-in. To ensure everyone has a chance, please sign up no more often than once every 2 weeks, but you can always drop in.
If none of these times work, let me know and we will work something out individually. Send a private note on Piazza with a few suggestions for times you are available. We may need to use Zoom. Other courses and discussions overlap the times above, so if you have a standing conflict, please do say something, I would love to meet with you.
Course Websites
| Site | What it is for | Link |
|---|---|---|
| Course Website | This syllabus, the schedule, lecture notes, project info and other supporting documents | rust4ds.github.io/ds210-fa26-lectures |
| Piazza | Announcements, questions and discussion | http://piazza.com/bu/fall2026/ds210 |
| Gradescope | Where you track assignments, submit your work, and see exams and course standings | https://www.gradescope.com/courses/1356101 |
| Echo360 | Will house lecture recordings | A1 link and B1 link |
| GitHub | Base repositories for each assignment, which you fork, and where you push your work | Multiple links, to be released |
Course Content Overview
By the end of the course you should be able to read and write programs in a compiled, statically typed language (Rust); explain how a program uses memory and why that affects its speed; form well-reasoned preferences between programs that produce the same output; and use the everyday tools of software work including the command line, version control, and automated testing. More than any single topic, the goal here is for you to come away able to explain what your code does and why you wrote it that way.
- Part 1: Tools and Your First Program (Weeks 1-3)
- Part 2: Building and Judging Programs (Weeks 3-4)
- Part 3: Structuring Data (Week 5)
- Review and Midterm 1 (Week 6)
- Part 4: Memory (Weeks 7-9)
- Part 5: Borrowing and Working with Data (Weeks 9-10)
- Review and Midterm 2 (Week 10)
- Part 6: Collections and Abstraction (Weeks 11-12)
- Part 7: Practice and Payoff (Weeks 13-15)
- Final exam: Monday, December 14, 12:00-2:00pm, in our room (CGS 505)
For a complete list of topics that will be kept up-to-date as we go through the term, see the Schedule.
How the course works
Grading
How your grade is calculated
Your grade will be determined as:
| Category | Weight | Breakdown |
|---|---|---|
| Exams | 50% | 15% midterm 1, 15% midterm 2, 20% final exam |
| Active engagement | 20% | 15% in-class activities, 5% pre-work and surveys |
| Code reviews | 15% | 5% each, for Projects 1, 2, and 3 |
| Autograded work | 15% | 5% each, for Projects 1, 2, and 3 |
All three projects use the same point structure:
| Each project | |
|---|---|
| Checkpoint 1 | 1% |
| Checkpoint 2 | 1% |
| Final submission - known tests | 2% |
| Final submission - secret tests | 1% |
| Code review | 5% |
| Total | 10% |
We will use Gradescope to track grades over the course of the semester, which you can verify at any time and use to compute your current grade in the course for yourself. I will also publish "standings" files periodically on Gradescope which will include your attendance and other graded records, along with course average projections after the first and second midterm periods.
Curves
I will use the standard map from numeric grades to letter grades (>=93 is A, >=90 is A-, etc). For the midterms and final, we may add a fixed number of "free" points to everyone uniformly to effectively curve the exam at our discretion - this will never result in a lower grade for anyone. However, I make an effort to design exams such that they result in a fair distribution without adding curve points, and only use this policy in exceptional circumstances. If this comes into play, it will be added after exam corrections, and exam grades will be capped at 100%.
Lectures and Discussions
Lectures will involve extensive hands-on practice. Each class includes interactive presentations of new concepts, small-group activities on paper and on laptops, and built-in review periods. Laptops (and tablets) stay closed unless we are actively coding, so I will print handouts of the lecture notes for you to write on. Because of this active format, regular attendance and participation are important and count for a significant portion of your grade (15%).
Discussions
Discussions will review lecture material, host project code reviews, and run proctored exam corrections. They will also adapt over the semester to the needs of the class.
Pre-work
Pre-work will be assigned before most lectures to prepare you for in-class activities. These typically include readings plus a single quiz question. We will also periodically ask for feedback and reflections on the course between lectures.
Mid-semester update: The pre-work grade will now be calculated by dividing the semester up into third and dropping 2 pre-works from each third, accounting for occasional conflicts and forgetting, similar to the attendance policy.
Attendance and participation
Since a large component of your learning will come from in-class activities and discussions, attendance and participation are essential and account for 15% of your grade.
Lecture attendance is recorded in a few different ways, and which one we use varies from day to day:
- In-class activity sheets, where your group writes down everyone's name and turns in the sheet
- In-class Gradescope tasks, submitted individually or as a group during lecture. Some of these ask for a password that I say out loud in the room and post nowhere else
- Cold-calling, which doubles as a check that the people marked present are the people in the room
I also take a headcount most days. If the headcount and the names I collect stop lining up, we will move to stricter methods, and they will be more annoying for all of us. Please do not sign in for someone who is not there.
Discussion attendance is similar, will be taken on weeks when we do not have code review or exam corrections, and will be done on paper or via gradescope or other tools, depending on the week.
This course follows BU's policy on religious observance - if you are absent due to a religious conflict let me know and this will not count against you. If you cannot attend classes for a while, please let me know as soon as possible so we can make a plan so you don't fall behind. If you miss a lecture, please review the lecture notes and lecture recording. If I cannot teach in person myself, I will send a Piazza announcement with instructions.
How attendance is calculated
The 15% is split evenly across three attendance periods, 5% each. Within a period, every session is worth points:
- Lecture is worth 1 point
- Discussion is worth 2 points
Each period contains 18 points of sessions, and you need 16 points to earn the full 5%. That creates an excused-absence allowance of 2 points per period, which is equivalent to two lectures or one discussion, no questions asked and no need to notify me. Extra points do not roll over to the next period.
| Period | Sessions | Points available | Points for full credit |
|---|---|---|---|
| 1 | Lectures 1-12, Discussions 1-3 | 18 | 16 |
| 2 | Lectures 13-27, Discussions 4 and 7 | 18 | 16 |
| 3 | Lectures 29-40, Discussions 9 and 11, plus your broken-week session | 18 | 16 |
Some discussions are not on this list, because they already carry their own consequences and do not need attendance points on top: the three code review sessions (D5, D8, D12) and the two exam corrections sessions (D6, D10).
Your broken-week session counts toward period 3 regardless of when it takes place (October for A and November for B).
Cold-calling
Sometimes in class I will ask folks to raise hands to answer questions, and at other times I will call on people who have not volunteered. Since this makes a lot of people nervous, I wanted to share a bit of detail here about how and why I do this.
Why I do it. In most classes, only a few people answer everything while everyone else listens, and it gets worse over the course of the semester. Cold-calling lets us hear more voices, and it tells me what is actually landing for the average student. It also helps folks get comfortable speaking up. Sometimes students who are "called in" this way turn into more engaged participants later. It also serves as a cross-check on attendance.
How I pick people. Each class, I generate a random list, weighted towards students who have not been called on recently or who have been absent. So if you answered something on Monday, you are unlikely to come up again on Wednesday, but it is always possible.
The questions are low-stakes. Some questions are open-ended, like asking about what you noticed or what you think will happen. At other times I might ask a review question with a clear right answer, but give you the chance to think and talk to a neighbor before I call on you.
You can always pass. "I don't know" is a fine answer. I might prompt you with a more basic question, or ask someone else to volunteer, but there is no penalty for passing or getting something wrong. I only track if I called on you and if you spoke, not what you said.
Projects
Projects are three assignments that make up all of your non-exam work. Each includes checkpoints, final automated tests, and a code review in your discussion section.
There are three projects, and they all run on the same four-week rhythm between exams:
- Released on a Friday
- Two checkpoints, on the next two Fridays, each worth 1%
- Due the Friday after that
- Code review, in your discussion section the following week
Projects are graded once. There is no process for improving your project grade after submission.
Checkpoints
Each project has two checkpoints: earlier deadlines where we run your code against a subset of the tests. Checkpoints exist to encourage and reward work on a project over time, and they let us find out who needs help well before the final deadline.
Missing a checkpoint is not the end of the world. Half of the final visible test points come from re-running the checkpoint tests at the final deadline. So a missed checkpoint costs you that checkpoint's point for being late, but the code itself still earns credit when you submit it. Checkpoints reward being on time; they do not punish you a second time for the same thing.
Checkpoint dates are listed on the schedule, and checkpoint tests will be marked as such in the project base repo.
Visible and secret tests
Some of the tests we grade you on are ones you can run yourself, and some are not.
- Visible tests come with the base repo. You can run them as often as you like and know exactly where you stand.
- Secret tests are run by us after the deadline. You will see your score on them, but not which ones failed.
Secret tests serve two purposes: to get you to think about the overall project and its edge cases in a realistic manner, and to mitigate the overuse of AI.
Working with other people's code
All three projects are individual work.
That said, learning git and GitHub is a major goal of this course, and git exists because real software is written by groups. So each project will involve realistic collaboration "events" staged by the teaching team to practice the tools and moves you'll need in the real world (more on that later).
You are always welcome to talk through approaches with classmates. See the collaboration policy below for where the line is.
Submitting your work
For each task, checkpoint, and project, we publish a Gradescope assignment. For coding work this will link to a base repository on GitHub. You fork it, do your work there, and commit as you go.
To submit, you paste the URL of your fork into Gradescope. We download your repository from that URL and run tests against it.
(If this language is new to you, that's okay! We'll go over all of it in Week 2.)
Everything you submit runs through GitHub, which means your commit history is part of what we see and evaluate.
Code reviews
Code reviews happen during your discussion section in the week following each deadline. A member of the course staff will go through your code and your commit history with you, ask you to explain specific choices, ask "what if" questions, and give you feedback.
You must attend your code review. If you need to reschedule, give us at least 2 days' notice and we will work with you to find another time.
We will review late submissions in whatever state they are in at the time of the code review - we will not postpone review because submissions are delayed.
If you do not attend a code review, you will receive a zero on the entire project, including the autograded portion, even if your tests passed. The code review is where you demonstrate that you understand the work you submitted, and passing tests does not show that on its own. This principle is reflected in the GenAI policy below.
Deadlines and late work
| What | Due |
|---|---|
| Checkpoints and projects | 11:59pm on the date specified in Gradescope |
| Lecture pre-work | 11am on the morning of each lecture |
Everything is due at midnight except pre-lecture work, which is due before the lecture it prepares you for.
If your work is up to 48 hours late, you can still qualify for up to 80% credit for the assignment. After 48 hours, late work will not be accepted unless you have made prior arrangements due to extraordinary circumstances.
Note that late project submissions still get reviewed on the normal schedule, in the discussion section following the deadline.
Exams
Exams are two midterms and a cumulative final exam covering theory and short hand-coding problems (which we will practice in class!).
| Exam | When | Where |
|---|---|---|
| Midterm 1 | Friday, October 9 | In class, normal lecture time, each section takes its own |
| Midterm 2 | Friday, November 6 | In class, normal lecture time, each section takes its own |
| Final | Monday, December 14, 12:00-2:00pm | CGS 505, our usual room. Combined across both lecture sections |
No external resources may be used in exams: no calculators, reference sheets, scrap paper, or electronic devices of any kind. Smart watches and glasses must not be worn, even if switched off.
If you have a valid conflict with a test date, you must tell me as soon as you are aware, and with a minimum of one week's notice (unless there are extenuating circumstances such as a medical emergency) so we can arrange a make-up test.
If you have accommodations for exams, please schedule all three dates (October 9, November 6, and December 14) with the testing center now, in the first two weeks of class. Historically, the testing center has booked up quickly. See below for more about accommodations.
Second chances
Exam corrections. About two weeks after each midterm, we hold proctored corrections during discussion section. You will have the opportunity to redo specific questions in person with your old, completed exam alongside a blank exam. Your final grade for that midterm will be the average of your original and corrected scores. (That is, you can earn back up to 50% of your lost points via corrections.)
A strong final exam counts for more. If you are struggling in the beginning of the course and make an effort to catch up, your grade will reflect that improvement. If your final exam score is higher than your midterm average, we reweight your exams automatically:
| Normally | If your final is higher | |
|---|---|---|
| Midterm 1 | 15% | 10% |
| Midterm 2 | 15% | 10% |
| Final exam | 20% | 30% |
You do not need to request this or do anything differently. We compute your grade both ways and use whichever is better for you. Your midterm average here is your score after any corrections.
Regrading
You have the right to request a re-grade of any assignment or test. All regrade requests must be submitted using the Gradescope interface. If you request a regrade for a portion of an assignment, then we may review the entire assignment, not just the part in question. This may result in a lower grade. We only restore missed points when a factual error was made in grading (such as misreading handwriting, or misclicking in Gradescope), not to respond to arguments for more partial credit. This keeps grading consistent and fair to all students.
Policies
Academic honesty
You must adhere to BU's Academic Conduct Code at all times. Please be sure to read it here. In particular: cheating on an exam, passing off another student's work as your own, or plagiarism of writing or code are grounds for a grade reduction in the course and referral to BU's Academic Conduct Committee. If you have any questions about the policy, please send me a private Piazza note before taking an action that might be a violation.
Collaboration
You are free to discuss problems and approaches with other students but must do your own code writing. If a significant portion of your solution is derived from someone else's work (your classmate, a website, an AI, etc.), you must cite that source in your writeup or comments. You will not be penalized for using outside sources as long as you cite them appropriately.
You must also understand your solution well enough to be able to explain it if asked.
AI use
You are allowed to use GenAI (e.g., Claude, ChatGPT, GitHub Copilot, etc.) to help you understand concepts, debug your code, or generate ideas. You should understand that this may help or impede your learning depending on how you use it.
This course is designed so that, largely, I do not have to police that choice. The parts of your grade that carry the most weight - exams and the code reviews on your projects - all require you to explain your work in person. If you lean on AI in a way that leaves you unable to explain what you built, that will become apparent during code review and on exams.
If you use GenAI on a project, you must cite what you used and how you used it (for brainstorming, autocomplete, generating comments, fixing specific bugs, etc.) in your project's README. You must also understand your solution well enough to explain it during a code review or in a follow-up conversation if asked. If it is determined that you overused GenAI to the extent that you fundamentally do not understand the code you submitted, you will receive a zero on the entire assignment, including the autograded portion, even if the autograded tests passed.
Your professor and TAs/CAs are happy to help you write and debug your own code during office hours, but we will not help you understand or debug code generated by AI.
For our departmental policy, see the CDS policy on GenAI. Note that this policy is in the process of being updated and parts of it do not apply in this course (for example, we do NOT require you to submit your entire chat history as an appendix). If you have any questions about the policy let us know.
Accommodations
If you need accommodations, let me know as soon as possible. You have the right to have your needs met, and the sooner you let me know, the sooner I can make arrangements to support you.
This course follows all BU policies regarding accommodations for students with documented disabilities. If you are a student with a disability or believe you might have a disability that requires accommodations, please contact the Office for Disability Services (ODS) at (617) 353-3658 or access@bu.edu to coordinate accommodation requests.
If you require accommodations for exams, please schedule all three dates, October 9, November 6, and December 14, at the BU testing center within the first two weeks of the semester while they still have plenty of availability.
Appendix: BU Hub Learning Outcomes
This course carries three units in BU's Hub: Quantitative Reasoning II, Digital/Multimedia Expression, and Creativity/Innovation. Each Hub area publishes a set of learning outcomes, and here we describe how this course meets those objectives. For students of the course, reading this section is not required.
Quantitative Reasoning II (QR2)
Outcome 1. Students will frame and solve complex problems using quantitative tools, such as analytical, statistical, or computational methods.
Every project asks students to work from a problem statement to a working program. Lectures give students the analytical tools to reason about candidate solutions, and about computational speed and cost, on the way to solving complex problems.
Outcome 2. Students will apply quantitative tools in diverse settings to answer discipline-specific questions or to engage societal questions and debates.
This course applies the quantitative tools of algorithm analysis (considering speed and asymptotic complexity) to many problems: search, sorting, memory layout, graph and game-tree traversal, and concurrency. Late in the term, the lectures on querying data and on calling Rust from Python connect this material back to the rest of the data science pipeline. We also discuss the impact of computing costs on energy use.
Outcome 3. Students will formulate, and test an argument by marshaling and analyzing quantitative evidence.
Each project asks students to make and test hypotheses and argue for their design choices. They must use quantitative evidence from their computational experiments to defend their decisions.
Outcome 4. Students will communicate quantitative information symbolically, visually, numerically, or verbally.
Symbolically, we use Big-O notation, which is how we state a claim about scaling. Numerically and visually, we use benchmark tables and plots, in lecture and in project writeups. Verbally, students defend their work in code reviews, where they explain out loud how their program works and answer questions from the teaching staff about their work.
Outcome 5. Students will recognize and articulate the capacity and limitations of quantitative methods and the risks of using them improperly.
This course focuses on programs that don't just work, but scale and work effectively and efficiently. In projects and on exams, students are asked to make judgements between similar programs that have the same output but that have different limitations around complexity, speed, and memory use. Students must also think holistically about their design decisions, recognizing that some metrics (speed, test coverage, memory use, code simplicity) trade off against each other, and good design requires good judgement in addition to quantification.
Digital/Multimedia Expression (DME)
Outcome 1. Students will be able to craft and deliver responsible, considered, and well-structured arguments, statements, or expressions using appropriate digital media.
Student projects are complex repositories including source code, documentation (a README), a test suite, potentially other media such as images, and a commit history. Projects are evaluated not only by an autograder for correctness, but by a conversation with a teacher who can assess the arguments, style, and the repo as a whole.
Outcome 2. Students will be able to reflect on the ethical use of digital media, considering relevant issues such as accessibility, intellectual property rights, citational practices, and other discipline-specific concerns.
Citations are required for projects in this course. We talk throughout about what it means for code to be "yours", especially in the era of generative AI, and the importance of taking responsibility for your code even if it was derived from multiple sources. We also discuss intellectual property and license types when learning about external crates.
Outcome 3. Students will be able to demonstrate an understanding of the capabilities of one or more digital communication technologies in their assignments.
The technologies of everyday software work are central in this course: the command line, git and GitHub, compilers and interpreters, and automated testing tools. When learning git, students learn best practices about digital collaboration on code projects, and see the version control process as both facilitating communication and producing documentation artifacts for those who come later.
Outcome 4. Students will be able to demonstrate an understanding of the fundamentals of digital communication, such as principles governing design, time-based and interactive media, and the audio-visual representation of qualitative and quantitative data.
Code is a designed artifact with a human audience, and we emphasize that throughout: code is not just something a machine reads, and good code has care put into naming, structure, formatting, and documentation. We frequently consider similar programs side by side and discuss which one we prefer and why. In each project, students collect and present quantitative analysis of their code's performance in defense of their design decisions.
Creativity/Innovation (CRI)
Outcome 1. Students will demonstrate understanding of creativity as a learnable, iterative process of imagining new possibilities.
1A Students practice creative and innovative thinking as an iterative process, for example by revising their ideas or their methodologies in response to feedback from peers or instructors.
The course's projects each run over about four weeks and are built for iteration: the task is released, there are two checkpoints a week apart to ensure progress over time, there is a final deadline with evaluation that overlaps the checkpoints in content to capture iterative improvement, and the project concludes with a code review where students present and defend their ideas and receive further feedback. Indirectly, the course's policy on exam corrections allows for a layer of feedback and reflection after an exam is initially graded, letting students demonstrate growth based on exam feedback.
1B Students will provide a metacognitive reflection, in which they evaluate their choices in relation to risk-taking or experimentation and identify individual and institutional factors that promote and/or inhibit creativity.
Project code reviews are conversations about design choices, where students are asked what they tried, what failed, and what would happen if further changes were made to their code. Each project also requires a written reflection in its README: what the student tried first, why they changed it, and what they would do with more time. The same README must record where generative AI was used and how.
1C Students generate a product based on the above processes.
Each project in this course is such a product.
Outcome 2. Students will be able to exercise their own potential for engaging in creative activity by conceiving and executing original work either alone or as part of a team.
All three projects are individual, and all three leave room for original design. Each also requires students to use a new software tool (git) to combine their own work with changes made by others, which is how software is built in practice. Project 3 adds a competitive component: students enter the strategies they designed into an automated tournament. There is no single correct answer there, and the strategies that perform well are usually the ones with an out-of-the-box approach.
Schedule
Everything in this table that occurs in the future is subject to change. Please check the pre-lecture tasks before each class. Project and exam dates should be stable; we will announce clearly if any need to move.
At a glance
| Week | Dates | Project milestones | Exams | Participation |
|---|---|---|---|---|
| 1 | Sep 2 - 4 | Getting set up. Nothing due | ||
| 2 | Sep 7 - 11 | Install session in discussion Project 1 released | ||
| 3 | Sep 14 - 18 | Project 1 checkpoint 1 | ||
| 4 | Sep 21 - 25 | Project 1 checkpoint 2 | ||
| 5 | Sep 28 - Oct 2 | Project 1 due | End of period 1 Wed Sep 30 | |
| 6 | Oct 5 - 9 | Project 1 code review Project 2 released | Midterm 1, Fri Oct 9 | |
| 7 | Oct 12 - 16 | Project 2 checkpoint 1 | ||
| 8 | Oct 19 - 23 | Project 2 checkpoint 2 | Midterm 1 corrections | |
| 9 | Oct 26 - 30 | Project 2 due | ||
| 10 | Nov 2 - 6 | Project 2 code review Project 3 released | Midterm 2, Fri Nov 6 | End of period 2 Wed Nov 4 |
| 11 | Nov 9 - 13 | Project 3 checkpoint 1 | ||
| 12 | Nov 16 - 20 | Project 3 checkpoint 2 | Midterm 2 corrections | |
| 13 | Nov 23 - 27 | Thanksgiving recess. Nothing due | ||
| 14 | Nov 30 - Dec 4 | Project 3 due | ||
| 15 | Dec 7 - 11 | Project 3 code review | End of period 3 Wed Dec 9 | |
| Finals | Dec 14 | Final exam, Mon Dec 14, 12-2pm, CGS 505 |
Participation periods split the attendance portion of your grade into three equal parts, 5% each. Each period holds 18 points of sessions (a lecture is 1 point, a discussion is 2) and you need 16 for full credit, so you have room to miss two lectures or one discussion in each. Points do not carry over between periods, so the dates above are worth knowing. Full details are in the syllabus.
Week by week
This table is wide, so you may need to scroll right to see all columns.
| Date | Lecture | Topic | Due | Discussion |
|---|---|---|---|---|
| Week 1 | No discussion | |||
| Wed Sep 2 | 1 | Welcome: what this course is, and why Rust | ||
| Fri Sep 4 | 2 | Hello shell: talking to your computer | ||
| Week 2 | Mon Sep 7: Labor Day, no class | Install session | ||
| Wed Sep 9 | 3 | Hello Rust: your first program, and why it is fast | ||
| Fri Sep 11 | 4 | Hello git: save points for your code | Project 1 released | |
| Week 3 | Git basics | |||
| Mon Sep 14 | 5 | Start to finish: build it, break it, fix it | ||
| Wed Sep 16 | 6 | Variables: types and their properties | ||
| Fri Sep 18 | 7 | Functions: parameters, returns, and expressions | Project 1 checkpoint 1 | |
| Week 4 | Review and practice | |||
| Mon Sep 21 | 8 | Control flow: branching and looping | ||
| Wed Sep 23 | 9 | Complexity: how to compare two programs | ||
| Fri Sep 25 | 10 | Sorting: complexity and recursion | Project 1 checkpoint 2 | |
| Week 5 | Handcode and code review prep | |||
| Mon Sep 28 | 11 | Structs: bundling data with methods | ||
| Wed Sep 30 | 12 | Enums: variants and match | End of participation period 1 | |
| Fri Oct 2 | 13 | Errors: Result, Option, and reading a file | Project 1 due | |
| Week 6 | Project 1 code review | |||
| Mon Oct 5 | 14 | Match, again: patterns, arms, and getting the value out | ||
| Wed Oct 7 | 15 | Review: everything before Midterm 1 | ||
| Fri Oct 9 | MIDTERM 1 | Project 2 released | ||
| Week 7 | Mon Oct 12: Indigenous Peoples Day, no class | A section discussion only | ||
| Tue Oct 13 | 17 | The stack: frames, and why it is fast | ||
| Wed Oct 14 | 18 | The heap: allocation, and why it is slower | ||
| Fri Oct 16 | 19 | Pointers: references, dereferencing, and unsafe | Project 2 checkpoint 1 | |
| Week 8 | Midterm 1 corrections | |||
| Mon Oct 19 | 20 | Pointer danger: seven ways C loses your memory | ||
| Wed Oct 21 | 21 | Ownership: the three rules, moves, and copies | ||
| Fri Oct 23 | 22 | Owning collections: Vec, String, and capacity | Project 2 checkpoint 2 | |
| Week 9 | TBD | |||
| Mon Oct 26 | 23 | Strings: why text is harder than it looks | ||
| Wed Oct 28 | 24 | Borrowing: the two rules | ||
| Fri Oct 30 | 25 | Borrowing in practice: functions, iteration, and lifetimes | Project 2 due | |
| Week 10 | Project 2 code review | |||
| Mon Nov 2 | 26 | Tests: writing them, and what to test | ||
| Wed Nov 4 | 27 | Review: everything before Midterm 2 | End of participation period 2 | |
| Fri Nov 6 | MIDTERM 2 | Project 3 released | ||
| Week 11 | TBD | |||
| Mon Nov 9 | 29 | Traits: shared behavior across types | ||
| Wed Nov 11 | 30 | Generics: one function, many types | ||
| Fri Nov 13 | 31 | Hashing: HashMap, HashSet, and O(1) lookup | Project 3 checkpoint 1 | |
| Week 12 | Midterm 2 corrections | |||
| Mon Nov 16 | 32 | Binary heaps: a tree stored in a Vec | ||
| Wed Nov 18 | 33 | Queues: VecDeque and the ring buffer | ||
| Fri Nov 20 | 34 | Trees: recursive types, from lists to game trees | Project 3 checkpoint 2 | |
| Week 13 | Wed Nov 25 - Fri Nov 27: Thanksgiving recess | B section discussions only | ||
| Mon Nov 23 | 35 | Ship your code: modules, crates, and Python | ||
| Week 14 | TBD | |||
| Mon Nov 30 | 36 | Iterators: closures and laziness | ||
| Wed Dec 2 | 37 | Threads: doing two things at once | ||
| Fri Dec 4 | 38 | Sharing data: Arc, Mutex, and data races | Project 3 due | |
| Week 15 | Project 3 code review | |||
| Mon Dec 7 | 39 | Review: rapid fire across the term | ||
| Wed Dec 9 | 40 | Review: long form, and your questions | End of participation period 3 | |
| Mon Dec 14 | FINAL EXAM, 12:00-2:00pm, CGS 505, both sections together |
Notes
- Tuesday Oct 13 is a Monday schedule. Lecture meets as usual but B discussions don't meet that week.
- Wednesday Nov 11 (Veterans Day) is a regular class day.
- Lecture A discussion sections do not meet during Thanksgiving week.
- The two weeks where only one set of discussion sections meets (Week of Oct 12 and Thanksgiving week) we will run standalone practice sessions that are not tied to that week's lecture material.
- Nothing is due over Thanksgiving break.
- Checkpoints are a week apart, two per project, for all three projects. Project 3 has Thanksgiving between its last checkpoint and the deadline.
- Weeks 1 and 2 have nothing due. They are for getting your tools installed and working, and we will be monitoring your progress via pre-lecture tasks and discussion. By the time Project 1 starts you will have everything you need to work on it.
Projects
About projects
Three projects make up most of your non-exam work (alongside pre-lecture tasks). Each project is graded on correctness and performance (via automated tests) and on a code review conducted by the teaching staff during discussion section.
All three projects are individual work. Each one also gives you practice with git and GitHub beyond just committing your own code: we will push updates to the base repository that you have to merge into work you have already changed, and you will open pull requests and have them reviewed.
There is no separate homework. The short warm-up exercises that would otherwise be homework are early checkpoints of each project.
| # | Topic | Released | Checkpoints | Due | Code review |
|---|---|---|---|---|---|
| 1 | Number guessing game | Fri Sep 11 | Sep 18, Sep 25 | Fri Oct 2 | Week of Oct 5 |
| 2 | Build your own Vec | Fri Oct 9 | Oct 16, Oct 23 | Fri Oct 30 | Week of Nov 2 |
| 3 | Tic Tac Toe, and a class tournament | Fri Nov 6 | Nov 13, Nov 20 | Fri Dec 4 | Week of Dec 7 |
Project 1 is a search problem. You will write several strategies for guessing a hidden number, then measure which one is fastest and explain why.
Project 2 is where we start working closely with memory and data structures. You will build your own version of Vec, first the easy (slow) way and then the way the real one works, with memory you allocate and manage yourself.
Project 3 will be a tournament. You will write an agent that plays Tic Tac Toe, then a harder version on a 5x5 board with walls and a time limit, and at the end of the term all of your agents play each other.
Checkpoints
Checkpoints are earlier deadlines where we run your code against a subset of the final tests. They exist to encourage a few weeks of steady work, rather than cramming, and so we can find out who needs help well before the final deadline. Checkpoints also align with the most recent lecture material and help ensure you don't fall behind.
Each project has two checkpoints, each worth 1% of your course grade.
Half of the final visible test points come from re-running the checkpoint tests at the final deadline, so a missed checkpoint costs you that checkpoint's point for being late, but the code itself still earns credit when you submit it.
Code reviews
Code reviews happen during your discussion section in the week following the deadline. A member of the course staff will go through your code and your commit history with you, ask you to explain specific choices, and give you feedback.
The code review is worth 5% of your course grade per project, which is half of each project's total and as much as all of its automated tests combined.
Project 1: Guessing Game
Welcome to your first project!
Here's a game that is probably familiar. Somebody picks a number and will not tell you what it is. You can ask questions, and only two kinds are allowed: is it exactly this? and is it bigger than this? How can you find the number using as few questions as possible?
It's a simple game, but it captures some of what you'll face throughout your career: a search space larger than you can reasonably check one at a time, and rewards for being clever and thrifty.
Over three weeks you will implement several strategies for playing this game, run all of them thousands of times, and make an argument about which method is best.
You will also practice with the software development tools you're learning while you're at it. You will make your own copy of a repository, clone it, commit as you go, and at one point in the middle we will change the code underneath you and you will have to merge our changes into yours. You will practice working at the command line, first in a toy exercise, and then as a way of navigating git and doing your development work on the rest of the project.
So... Checkpoint 1 is not actually about the guessing game. It is a shell-based role-playing dungeon (!), and it is here to give you practice moving around on your computer at the command line before taking on the full project. It shares the repo so that you only set things up once, but it's really separate work, and you can finish it before you write any real Rust.
What is due when
- Checkpoint 1, Friday September 18. The dungeon only
- Checkpoint 2, Friday September 25. Implementing four guessing strategies
- The project, Friday October 2. Everything else, and the writeup
- Code review, in discussion the week of October 6.
Meet your project repo
Your starting point is https://github.com/rust4ds/ds210-fa26-project-1.
On GitHub, click Use this template, then Create a new repository. Name it ds210-fa26-project-1, the same as ours, and set it to Private. Then clone it. Work in your copy and push to it. That repo is what you submit at each checkpoint.
The template repo arrives in two pieces. To start, what you clone has checkpoint 1 in it. The guessing game itself, and the tests for it, come in an update you will merge around September 21. Files marked (Sep 21) below are not in your clone at first.
src/
dungeon.rs your answers from checkpoint 1
game.rs play a game yourself against the computer
measure.rs run many games and report what happened (Sep 21)
plot.rs run every strategy, draw the plot, print the table (Sep 21)
secret_keeper.rs the other side of the game: who knows the number, and answers (Sep 21)
strategies.rs every guessing strategy, examples plus ones you write (Sep 21)
tests.rs every test in the project
version.rs which release of the base repo you have
dungeon_transcript.txt your bashcrawl session from checkpoint 1 goes in here
.gitignore a gitignore file that already takes out `target` and some cruft
Cargo.lock for now, you can ignore - it's about dependencies
Cargo.toml for now, you can ignore - it's about dependencies
README.md it starts as some instructions, and is where you'll put your write-up
From checkpoint 2 onward, everywhere you have to write code is marked todo! and the program will stop there if it reaches one. Only change the functions marked todo!. Checkpoint 1 has no todo!s: there, the things you change are the constants in dungeon.rs, your session in dungeon_transcript.txt, and the Author line of README.md.
Getting the update
The rest of the project arrives as a second commit on our template repo, and you pull it into your own copy. You'll do this once, the first time you start working towards checkpoint 2.
First, tell git where our repo is. origin is already your copy; upstream will be ours. From your repo, you can paste this into the terminal:
git remote add upstream https://github.com/rust4ds/ds210-fa26-project-1.git
git fetch upstream --tags
Becuase your repo was made with Use this template, you started with a clean history of your own. That means git doesn't know your repo and ours are related, and it will refuse to merge two histories it thinks are strangers. This next command tells git how they are related, by matching up the beginning of your repo with the beginning of the template. You can also paste this in exactly:
git merge -s ours --allow-unrelated-histories phase1 -m "connect this repo to the template"
Now you're ready for the merge itself:
git merge upstream/main
Expect one conflict, in src/dungeon.rs. We changed a line that you also changed to pass checkpoint 1, and git will refuse to guess which version you meant. Run git status to see it, then open the file. Like we practiced in Discussion 2, the two versions are marked off like this:
<<<<<<< HEAD
what your copy says
=======
what our copy says
>>>>>>> upstream/main
Your job is to decide how to combine those versions and delete all the marker lines. (This might take a second to think about - try to figure out why each side made a change, and whether you want to take one version, the other, or a hybrid of the two.) When it looks right:
cargo test --bin game cp1
should all pass again. And then you save as usual:
git add src/dungeon.rs
git commit -m "merge the project update"
git push
Then run cargo test --bin game cp2. It should run and fail, because you have not started the checkpoint 2 work yet! If it says there are no tests to run, you didn't successfully merge the update yet.
Running your project
cargo run --bin game -- --strategy random # play a game yourself
cargo run --bin game -- --strategy bad --min 2 --max 6
cargo run --bin game -- --help # every option
cargo run --bin plot # writes plot.png and prints the table
Playing against your own strategy is the fastest way to see what it does. Use a small range and you can follow every question.
None of these work until the September 21 update arrives. For checkpoint 1 the only command you need is cargo test --bin game cp1.
Running the tests
cargo test --bin game cp1 # your dungeon answers
cargo test --bin game cp2 # do your strategies work, and work as asked?
cargo test --bin game cp3 # everything else
cargo test --bin game # all the tests at once
Each test is named for a single function and a single thing that can go wrong with it, so a failing test can point you specifically to what's broken. The filter is a substring of the test's name, so
cargo test --bin game cp2::binary and cargo test --bin game shifted both work if you want to just run individual or a small set of tests.
When you first clone your repo, every test will fail and you'll see a lot of warnings, and that's to be expected until you start writing your code.
Things you will see before we teach them
A couple things in this repo come from lectures you haven't had yet, and you don't need to understand them fully.
&mut in front of the secret keeper. Every strategy is handed keeper: &mut SecretKeeper. The &mut says the function is allowed to change the keeper, which it does. We will cover this properly in October.
The tests themselves. src/tests.rs uses #[test] and assert_eq!, neither of which you have seen. You are not writing any tests in this project, so you only need to be able to read them, and you can probably get the gist of them without knowing exactly how testing works in Rust. We'll learn how to write tests in November.
There is also a lot of Rust in secret_keeper.rs and plot.rs which will look unfamiliar, but you'll never modify these and aren't responsible for understanding their details.
Submitting
To submit a checkpoint and your final project, see the appropriate Gradescope assignment which will prompt you to log into GitHub and then point to your project repo. That's it! Your repo can stay private, you are just granting Gradescope permission to read it.
There is one Gradescope assignment per checkpoint. Push your work to GitHub before you submit, because Gradescope reads your GitHub repo and not your local copy.
Checkpoint 1: the dungeon
Before you can write Rust you have to be able to get around a computer without a mouse.
Bashcrawl is a dungeon you explore from the command line. Rooms are directories, and you navigate with cd, look around with ls and read files with cat. There are no graphics and nothing to install beyond the game itself.
Play the game, answer the questions it raises, and keep a record of what you typed.
Getting the dungeon
Clone our copy, not the one you might find by searching:
git clone https://github.com/rust4ds/bashcrawl.git
cd bashcrawl
cat README.md
Ours has a few fixes in it, and the answers the tests expect are the ones our copy gives.
Recording your session
You have to hand in a transcript of everything you typed. Don't tidy it up, since wrong turns, typos and dead ends are all fine, and demonstrate your process. Save the transcript to a file called dungeon_transcript.txt in your project repo (outside of src).
On Mac, press command-S and save the window's contents to a file.
On Git Bash (Windows), right-click inside the terminal window and choose Select All from the menu, then right-click again and choose Copy. (Dragging to highlight the whole window works too.)
Either way, paste what you get below the line in dungeon_transcript.txt.
Whatever you do, do not close the terminal until you have saved. There is no way to get the session back afterwards. If you are playing in more than one sitting, save at the end of each one and paste them in one after the other in the transcript.
Explore and take notes!
Look at src/dungeon.rs for the questions you're trying to answer as you go to guide your exploration. Take notes on your answers as you go and enter them as values in dungeon.rs. Once you get to the last answer you've gone far enough, but as a bonus (and maybe for bonus credit on a secret test...) try to beat the game completely.
A few hints for if you get stuck (try first on your own!):
- Take the treasure in the cellar. If you are back at the entrance and there is nothing new to see, you may have missed this.
- Quick portal to the pit. Once you have taken the treasure, a scrap of paper turns up back at the entrance describing how to summon a portal. A portal is a symbolic link, which is a shortcut from one place to another (like an alias). The spell written on the scrap only works from one particular room deep in the dungeon, so if you would rather not go hunting for that room, run this from
entranceinstead:
ln -s ./.rift portal
cd portal
- The robot is optional. In the satellite there are four pieces of a robot and a notebook explaining how to put them back together. There's a right way to check, but you can also just try both remaining options to see which one works. Moreover, none of the graded answers are behind the robot, so this is just for fun.
- The graveyard is also optional. There is nothing you need for the answers in there, so visit it if you are interested and otherwise skip it.
- Winning the game depends on decisions you made earlier and a bit of luck, and is not required for passing the checkpoint tests.
Checklist
- Make your own private copy of the Project 1 repository with Use this template, then clone it to your own machine (done in Lecture 4's Activity)
-
Put your name on the Author line of
README.md - Clone bashcrawl and start recording your session
- Play bashcrawl through to answer the questions
-
Fill in the constants in
src/dungeon.rswith what you found -
Check
dungeon_transcript.txthas your session in it -
Check that
cargo test --bin game cp1passes - Commit, push, and submit your repo on Gradescope
Hints and tips
cd ..goes back up one roomlsdoes not show you everything.ls -aalso shows hidden files, the ones starting with.- Read every file you find with
cat - If you get lost,
pwdtells you where you are - Try tab-completing to speed things up and prevent typos
- Use the up arrow to bring back previous commands, and down to go the other way
- If you get stuck mid-command (like in a
dquote!) control-c is your friend
Checkpoint 2: four strategies
Somebody picks a number and writes it down. You do not get to see it. All you can do is ask them questions, and only two kinds are allowed:
- "Is it exactly 7?" They answer yes or no.
- "Is it bigger than 7?" They answer yes or no.
A strategy is a plan for which questions to ask, and in what order, so that you end up knowing the number. You write it as a function. It plays one whole game, from the first question to the answer:
#![allow(unused)] fn main() { pub fn binary(keeper: &mut SecretKeeper, min: u32, max: u32) -> u32 }
keeperis the person who knows the number. You ask them thingsminandmaxare the range the number is somewhere inside,minincluded andmaxnot- the
u32you return is the number you have worked out
Two things about that signature:
- Each question comes back as a
bool, but the strategy returns a number. - The whole game happens inside one function call. You don't call your function once per question, but once per game.
All four strategies will get the right answer, but what separates them is how many questions that takes, and in checkpoint 3 you will be able to measure how much it matters.
What you are writing
You'll complete most of the functions in src/strategies.rs for this checkpoint. Read bad and random at the top first which can serve as templates. The four functions in Search strategies and the constant are yours to edit at this point. More about each:
linear. Try min, then min + 1, upward, asking ask_if_equal each time.
binary. Ask ask_if_greater about the midpoint and throw away the half that cannot contain the number. Narrow until one number is left, and do not spend a question confirming it.
jump. Step forward STRIDE at a time with ask_if_greater until the number is behind you, then go back to the stretch you jumped over and check the numbers in it one at a time with ask_if_equal, working upward from the bottom of that stretch. STRIDE comes set at 1, which works and is the worst possible choice. Pick something better and be ready to explain why.
lucky. Binary search, but before narrowing, spend one question asking outright whether the midpoint is the number. Sometimes that wins the game on the spot. Whether it is a good trade overall is a checkpoint 3 question, so do not decide yet.
What if you run out of numbers? Every strategy assumes the answers it gets are honest, and if they are, linear and jump will always find the right answer before the end of their loops. The compiler can't know that, though, so needs to be told what to do if the loops finish without encountering a yes answer, and what it does has to be compatible with the function's return type. You have a couple valid options here - how you handle it matters less than that you handle it so the code compiles.
The tests ask two things. Eight tests check that a strategy finds the secret number. The other four count how many questions it spent doing it to make sure you're writing the right strategy for each. For example, if binary passes binary_finds_every_number and fails binary_costs_log_of_the_range, it is finding the number, just not guessing the numbers in the correct order for the binary strategy.
Checklist
-
linearworks.cargo test --bin game cp2::linear -
binaryworks.cargo test --bin game cp2::binary -
jumpworks, andSTRIDEis something better than 1.cargo test --bin game cp2::jump -
luckyworks.cargo test --bin game cp2::lucky -
cargo test --bin game cp2is entirely green, twelve tests - Commit, push, and submit your repo on Gradescope
Hints and tips
Here is an example run of binary finding the number 73 on the range [0, 100):
Q1: is it greater than 49? -> YES
Q2: is it greater than 74? -> no
Q3: is it greater than 62? -> YES
Q4: is it greater than 68? -> YES
Q5: is it greater than 71? -> YES
Q6: is it greater than 73? -> no
Q7: is it greater than 72? -> YES
returns 73, after 7 questions
Notice that it never asks whether the number is 73.
Here is jump on the same number, with STRIDE set to 10:
Q1: is it greater than 0? -> YES jump forward to 10
Q2: is it greater than 10? -> YES jump forward to 20
Q3: is it greater than 20? -> YES jump forward to 30
...
Q9: is it greater than 80? -> no stop: it is somewhere in 71..80
Q10: is it exactly 71? -> no
Q11: is it exactly 72? -> no
Q12: is it exactly 73? -> YES
returns 73, after 12 questions
More tips:
- Play against your own code to watch it run:
cargo run --bin game -- --strategy binary --min 0 --max 16. Sixteen numbers is small enough to follow every question and check the answers yourself - Remember that some of the final tests are not in this file, they're "secret". The final autograder runs your strategies on ranges you have not seen: bigger ones, smaller ones, and ones somewhere else on the number line. Make sure your functions don't just pass the tests, but are correct for any inputs we could give.
- Commit each strategy as you finish it. It will give you a checkpoint to come back to if you get lost, and it will help tell your development story when it comes time for code review.
- Read your compiler errors. Remember that even if you know your function is exhaustive and will hit a
returninside a loop, the compiler doesn't know that and you may need toreturnat the end of your functions even if that is never reached. The error you might encounter for this though is a bit obscure - it will look likemismatched types: expected u32, found ()or similar (you'll understand more about why it looks like that later!)
Checkpoint 3: measuring, and one more strategy
You have four strategies that work, now you'll find out which one is the best (if you haven't already guessed).
In this checkpoint you will write the thing that runs thousands of games and reports what happened, and then one last strategy that beats binary search by noticing something about the game the other four have so far ignored.
What the other four ignore. The dealer never uses the same secret twice until it has used them all (have you noticed?). So by the 50th game of 100, half the numbers cannot possibly be the answer, and that gives you an advantage. Binary searches all 100 anyway, but you can do better. We won't guide you to the optimal strategy (though you should think about it!) but we'll make a clever little improvement with this information to create a strategy called... clever (clever name, huh?).
To use clever you need to be able to ask two things about a range of numbers: how many
numbers in it could still be the secret, and which is the first one that could. These are both calculations based on the historical games you've seen so don't "cost a question". So you'll write those two helpers first and then clever on top of them.
What you are writing
Six things, in three files.
1. measure and is_better_than, in src/measure.rs. Play rounds games of one strategy and report the best, the mean, the worst and the standard deviation across them. match on approach to decide which strategy plays. Read the doc comment above the function before you start: it says where the games come from. Decide what to return when rounds is 0, and be ready to explain why.
Underneath it, is_better_than compares two of those reports and says which strategy you would rather use. The signature is written for you, so you only write the body, and you decide what better means: a lower mean, a better worst case, some combination, etc. Many rules will pass as long as they're reasonable, and you'll just have to defend your decision if asked at code review.
2. possible_count and first_possible, in src/strategies.rs. The two questions described above, as functions. One counts how many numbers in a range could still be the secret; the other finds the first of them.
first_possible returns an Option<u32> rather than a plain u32, because there is a case where it has no answer to give, and a function forced to return something ends up returning a number it does not mean. Work out when that case happens, and what you want the None arm to do about it.
3. clever, in src/strategies.rs.
We're not going to rework the whole algorithm, just the end. Binary keeps going until one number is left between min and max. You can stop as soon as one possible number is left, because at that point there is nothing else it could be. You'll need to change two things from the code for binary and can use first_possible and possible_count to get there.
4. Refactor jump. Look at the second half of the jump you wrote for checkpoint 2. It walks the numbers it skipped, one at a time, asking ask_if_equal about each. That is basically your linear strategy! So just make jump call linear instead.
One thing does have to change under the hood. linear counts upward, so the walk has to run upward too: from the bottom of the stretch you jumped over, not backward from the number you overshot. But nothing in the statistics or tests changes when you do this (do you know why?). Your Checkpoint 2 tests should still pass after this!
5. Fix your midpoint, in src/strategies.rs. binary and lucky both work out a midpoint. If you wrote yours as (lo + hi) / 2 in CP2 it passed then but now fails the new test binary_survives_the_top_of_u32. Figure out what the issue is and find a way to reach the same midpoint without computing (lo + hi) to pass the test.
6. The writeup, in the README of your repo. Copy over the questions at the end of this page into your README and answer them. They ask you to explain your own numbers, so you cannot answer them until your code runs and plot.png exists. This counts towards the first part of your code review grade.
Checklist
-
measurereports all four numbers.cargo test --bin game cp3::measure -
is_better_thanpicks a winner.cargo test --bin game cp3::is_better_than -
possible_countandfirst_possiblework.cargo test --bin game cp3::possibleandcp3::first_possible -
cleverworks and beats binary over a sweep.cargo test --bin game cp3::clever -
jumpcallslinear.cargo test --bin game cp3::jump_calls_linear -
binarysurvives a range at the top ofu32, and you fixedluckythe same way.cargo test --bin game cp3::binary_survives -
cargo run --bin plotproducesplot.png, and you have committed it -
cargo test --bin gameis entirely green - The writeup is answered in your README
- Commit, push, and submit your repo on Gradescope
Hints and tips
- Read the
cp3tests before you start writing. They make it clear how long each strategy is supposed to take measureneeds the mean before it can work out the standard deviation, and you cannot replay the games for a second look, because the dealer has moved on. Keep running totals instead: the counts, and their squares. Variance is the mean of the squares minus the square of the mean.- If
cleverreturns the wrong number, the bug is probably in what you return at the end rather than in when you stop - Run
cargo run --bin plotearly, even with strategies half finished to get a feel for what's happening
The writeup
Your writeup goes in the README of your repo, under the headings that are already there. Leave the rest of that file alone.
You can write 2-3 sentences per question unless it says otherwise.
Reading the plot
Look at plot.png. The X axis is max, the range the strategy had to search. The Y axis is how many questions it needed.
1. Which strategy is best according to plot.png? Refer to the curve and define what you mean by "best". Then look at the ranking printed under the table, which is your own is_better_than putting the same strategies in order: what rule did you give it, and does the order it produced agree with what you just said about the plot? If they disagree, which one do you believe, and why?
2. Look at linear. If max = 110, how many questions will it ask? What about max = 120? Now write it as a function of n.
3. Look at binary. Many values of max give the same number of questions, and then it steps up. Where do the steps happen? Counting max = 1, there are seven of them on this plot. Is there a pattern? Predict where the next one is, then write binary's cost as a function of n. Hint: it has something to do with powers of 2.
4. Jump search sits between the other two. Its curve is neither flat like binary's nor straight like linear's. What shape is it, and why? What stride did you pick, and what happened when you tried a different one?
Reading the table
5. The lucky strategy can find the number in one question where binary needs six, and yet lucky's mean is much higher. Explain why the extra question costs more than it gains, in terms of what each of the two questions tells you when the answer is no.
6. Now look at the best column of your table. Linear, lucky, and random can all find the number in a single question if they get lucky. Binary never can (but it beats the rest four on average anyway). Jump can't get it in one step either. Explain why.
Going further
7. Suppose we gave you a third question, ask_if_even, costing one question like the others. Could you use it to beat binary search? Say why or why not.
8. plot.png does not have a curve for clever. Why do you think it was excluded, and if we did include it, what do you think it would show? Hint: Take a look at the plot.rs code and investigate the role of the dealer and history there.
Process
9. What's something you tried that failed at first on this project, and how did you adapt?
10. Before checkpoint 2 we changed the base repo underneath you and you had to merge it. How did you decide what to keep when the changes conflicted, and how did you check that you were right?
Your AI citation. Who and what you used, and how. Course policy is in the syllabus.
Project 2: Build Your Own Vec
Welcome to your second project!
We have been using Vec throughout our time with Rust, and lists in almost every Python program before that. You can push things onto the end and the list grows. But memory doesn't grow. When a program asks for a block of memory it gets exactly that much, and the block can never get bigger. So how does a Vec hold a million elements when it started out holding none?
In this project you will build your own Vec, twice. First a slow version that is safe and simple, then a fast one that manages its own memory by hand with raw pointers. Then you will race them and explain what you see.
This project runs alongside the memory unit in lecture: the stack, the heap, pointers, ownership, and borrowing. You will ask for memory, put values into it, move them around, and give the memory back, and when you get one of those wrong you will see exactly what Rust's rules have been protecting you from.
You will also practice a new git workflow: each checkpoint lives on its own branch, which you merge into main with a pull request when it is done. In checkpoint 3 you will use branches for something else they are good for, which is trying out ideas without committing to them.
What is due when
- Checkpoint 1, Friday October 16.
SlowVec - Checkpoint 2, Friday October 23.
FastVec'sgetandpush, and how it grows - The project, Friday October 30.
remove,clear,Drop, the benchmark, and the writeup - Code review, in discussion the week of November 2.
Checkpoint 1 is short on purpose, since it falls the week after the midterm. Checkpoint 2 is the hardest part of the project, so leave yourself time for it.
Meet your project repo
Your starting point is https://github.com/rust4ds/ds210-fa26-project-2.
Same as Project 1: on GitHub, click Use this template, then Create a new repository. Name it ds210-fa26-project-2 and set it to Private. Then clone it.
This time the whole project arrives at once. There is no update to merge partway through.
slow_vec/ Part 1
src/lib.rs SlowVec. Your push and remove go here
src/playground.rs a scratch pad for trying SlowVec out
src/memory.rs watches what gets dropped, and when
tests/cp1.rs the checkpoint 1 tests
fast_vec/ Part 2
src/lib.rs FastVec. Your get, push, remove, the clear fix and Drop go here
src/growth.rs how a FastVec picks its new size. Yours
src/timing.rs timing pushes, for the benchmark. Yours
src/benchmark.rs runs the benchmark and draws the plots. You choose what it compares
src/playground.rs a scratch pad for trying FastVec, MALLOC and pointers out
src/memory.rs watches what gets dropped and freed, and when
tests/cp2.rs the checkpoint 2 tests
tests/cp3.rs the checkpoint 3 tests
fixed/ FixedSizeArray, which SlowVec is built on
malloc/ the memory allocator FastVec uses
tracker/ wraps values so you can see when they are dropped
README.md instructions to start, and where your writeup goes
You will only edit files in slow_vec/ and fast_vec/. The other three folders are tools we built for you. You are welcome to read them, but shouldn't edit them.
Everywhere you have to write code is marked todo!, and the program stops if it reaches one. Only change what this page asks you to: the functions marked todo!, the Drop for FastVec, your choices in benchmark.rs, and the writeup in README.md.
Working on branches
In Project 1 you may have committed straight to main. This time, each checkpoint's work happens on its own branch, and only reaches main through a pull request once it works.
Start checkpoint 1 like this, from inside your repo:
git switch -c checkpoint-1
switch -c makes a new branch and moves you onto it (git checkout -b checkpoint-1 also works for this). Commit as you go, the same as always. The first time you push the branch, tell git where it goes:
git push -u origin checkpoint-1
After that, plain git push works.
When the checkpoint's tests pass, merge it into main with a pull request:
- On your repo's GitHub page, open the Pull requests tab and click New pull request
- Set base to
mainand compare tocheckpoint-1. GitHub shows you every change the merge would bring in. Read it over - Click Create pull request, give it a title, then Merge pull request
Then bring the merged main back to your laptop, and start the next checkpoint's branch from it:
git switch main # or git checkout main
git pull
git switch -c checkpoint-2 # or git checkout -b checkpoint-2
Gradescope will just grade the branch you point it to (which should be main), so you'll need to merge your pull request before submitting on Gradescope.
We will look at your branches and pull requests at code review, using git log --graph --all --oneline. Try that command yourself now and then. It draws your branches as lines, and it's a great way to see what git thinks is going on.
Running your project
Everything runs from the top folder of your repo:
cargo run --bin slow_playground # try out SlowVec and FixedSizeArray
cargo run --bin slow_memory # watch what SlowVec drops, and when
cargo run --bin fast_playground # try out FastVec, MALLOC, and raw pointers
cargo run --bin fast_memory # watch what FastVec drops and frees, and when
cargo run --release --bin benchmark # time your vectors and draw the plots
The playgrounds are yours to edit, and aren't graded. You can use them to try things out and see how they work.
Open that same top folder in VS Code, with code . from inside it, so that rust-analyzer sees the whole workspace and gives you types and errors as you type. If you open the folder above it instead, there is no Cargo.toml to find and you get no hints. If the status bar says rust-analyzer could not find a project, the reload steps are in Discussion 1.
Running the tests
cargo test --test cp1 # SlowVec
cargo test --test cp2 # FastVec's get and push, and growth
cargo test --test cp3 # remove, clear, Drop, and timing
cargo test # all the project's tests
Add part of a test's name to run only the tests that match it: cargo test --test cp2 memory, or cargo test --test cp2 growth.
When you first clone your repo, almost every test fails and you'll see a lot of warnings. Like in the last project, that's expected until you start writing your code.
If a test run stops partway with SIGSEGV, SIGBUS, SIGABRT, or some other signal, one of your unsafe blocks has corrupted memory, and it took the whole run down with it. That only becomes possible in checkpoint 2. The last test named before the crash is where to start, so run it on its own.
Things you will see before we teach them
<T>. SlowVec<T> and FastVec<T> work for any type of element: SlowVec<i32>, SlowVec<String>, SlowVec<bool>. The T stands for "whichever type the vector holds". You've seen them before in things like Vec<T>, Option<T>, and Result<T, E>. This is called a generic, and we cover generics properly in November.
impl Display for SlowVec<T> and impl Drop for FastVec<T>. These are traits, also a November topic. Display is what lets println!("{}", v) print a vector, and it is written for you. You will write the body of a Drop yourself in checkpoint 3, and this page gives you the outline. You can work with them just like implementing methods on enums and structs with impl.
Submitting
As with Project 1, each checkpoint and the final project will have its own Gradescope assignment, which asks you to log into GitHub and point it at your repo. Pick the main branch. Merge your pull request and push before you submit, because Gradescope reads GitHub, not your laptop.
Checkpoint 1: SlowVec
Our first vector is the simplest one that could possibly work. It is slow, and in checkpoint 3 you will measure exactly how slow, but it is safe, short, and it sets up everything that comes after.
What you are given: FixedSizeArray
SlowVec is built on a type we wrote for you, FixedSizeArray. It is a row of slots, and it can never change size. You decide how many slots when you make one, and that is how many it has forever.
It has five functions:
FixedSizeArray::allocate(n)makes a new array with exactlynempty slots.put(element, i)storeselementin sloti.get(i)returns a reference to the element in sloti, written&T.move_out(i)takes the element out of slotiand gives it to you, writtenT. The slot is empty afterwards.len()tells you how many slots it has
The difference between get and move_out matters a lot. Think of a reference as a read-only view of the element: get lets you look, and the element stays where it is, so you can get the same slot as many times as you like. move_out hands you the element itself, and the array no longer has it. You can only move_out a slot once, until something is put back in it.
Try it. Open slow_vec/src/playground.rs and run it:
cargo run --bin slow_playground
The program prints some output, then crashes, because push and remove are not written yet. Look at fixed_sized_array() first. It calls get twice and move_out once. Uncomment the second move_out and run it again. What happens? What if you get a slot after you move_out of it?
What you are writing
Open slow_vec/src/lib.rs. SlowVec is a struct with one field, fixed, which is the FixedSizeArray holding its elements. Most of its methods are written for you: new, len, get, clear, and two for converting to and from a regular Vec, which the tests use.
Every method takes some form of self first. Like with structs, it refers to the particular SlowVec the method was called on, so in my_vec.push(5), self is my_vec and self.fixed is my_vec's array.
Your job is to write two methods, push and remove.
Here is the problem with both of them. self.fixed cannot change size. So you cannot add a slot to it for push, or take one away for remove. What you can do is make a new array of the right size, move every element across into it, and replace the old one:
// 1. Make a new FixedSizeArray. One slot bigger for push, one smaller for remove.
// Which method on SlowVec tells you the current length?
let mut tmp = /* create a FixedSizeArray of the right size */
// 2. Move every element out of self.fixed and into tmp.
// For push, put the new element in the end.
// For remove, skip the element that's removed and close up the gap.
// 3. Replace the old array with the new one.
self.fixed = tmp;
When the last line runs, the old array is thrown away and its memory goes back to the computer. You don't have to do anything to make that happen. Hold that thought until checkpoint 3.
Run slow_playground again when you think you're done. In slow_vec_push() and slow_vec_remove(), the comment next to each println! says what it should print.
Then run slow_memory, which uses our Tracker to watch your elements and reports any that are never cleaned up. Yours will all be cleaned up, and it is not because you were careful: safe Rust does not let you lose track of them. In part 2 that guarantee goes away, and this tool will be how you find your mistakes.
Checklist
- Make your own private copy of the Project 2 repository with Use this template, then clone it
-
Put your name on the Author line of
README.md -
Make a
checkpoint-1branch -
pushworks -
removeworks -
cargo test --test cp1is entirely green, twelve tests -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Read the
memorytests incp1.rs. They watch every allocation and free, so they check thatpushmakes exactly one new array of the right size, and that the old one is given back. If one fails, the transcript of allocations in its message says what you did instead - For
pushandremovetry writing out what the arrays look like before and after for a small case before coding them up - Consider whether you need to use
get,move_out, neither, or both in your methods - If your tests suddenly won't compile, check the playgrounds too!
Checkpoint 2: FastVec
SlowVec copies the entire vector on every single push. If you push a million elements to an array by looping over them, the array gets copied and moved 999,999 times. Rust's Vec and Python's lists don't work that way, and our FastVec won't either.
Making it fast takes two ideas: leaving room to grow, and managing the memory yourself.
Idea 1: length and capacity
SlowVec only ever has exactly as many slots as it has elements. FastVec keeps track of two numbers instead:
- its length: how many elements it holds right now
- its capacity: how many it has room for before it has to grow
When the length is less than the capacity, a push is cheap: put the element in the next empty slot, and you're done. Only when the vector is full does it have to grow, by allocating a bigger block, moving everything across, and freeing the old one, just like SlowVec.
The trick is in how much bigger. SlowVec grows by one, so it is full again immediately. If FastVec doubles its capacity every time it grows, the resizes get further and further apart.
Here is what happens when you push 8 elements into a new FastVec, which starts with capacity 1. Count one step for every element written or moved:
| Push | Before: length, capacity | What happens | Steps | After: length, capacity |
|---|---|---|---|---|
| 1 | 0, 1 | room, just write it | 1 | 1, 1 |
| 2 | 1, 1 | full, grow to 2: move 1, write 1 | 2 | 2, 2 |
| 3 | 2, 2 | full, grow to 4: move 2, write 1 | 3 | 3, 4 |
| 4 | 3, 4 | room | 1 | 4, 4 |
| 5 | 4, 4 | full, grow to 8: move 4, write 1 | 5 | 5, 8 |
| 6 | 5, 8 | room | 1 | 6, 8 |
| 7 | 6, 8 | room | 1 | 7, 8 |
| 8 | 7, 8 | room | 1 | 8, 8 |
That is 15 steps for 8 elements, under 2 per push. SlowVec would have taken 1 + 2 + ... + 8 = 36. The gap gets wider the more you push, and in the writeup you will explain why.
Idea 2: managing memory yourself
FastVec does not use FixedSizeArray. Instead it asks for raw memory, and keeps track of what is in it on its own. The struct for FastVec holds a pointer to the start of its memory, plus the length and capacity:
pub struct FastVec<T> {
ptr_to_data: *mut T,
len: usize,
capacity: usize,
growth: Growth,
}
*mut T is a raw pointer: an address in memory, where Rust trusts you that a T lives. You met these in lecture on October 16.
Here is a FastVec holding five numbers, drawn the way we draw a Vec in lecture:
Stack: Heap (from MALLOC):
┌───────────────────────┐ ┌────┬────┬────┬────┬────┬────┬────┬────┐
│ v: FastVec<i32> │ │ 10 │ 20 │ 30 │ 40 │ 50 │ ?? │ ?? │ ?? │
│ ├ ptr_to_data ────────┼──────────▶│ │ │ │ │ │ │ │ │
│ ├ len: 5 │ └────┴────┴────┴────┴────┴────┴────┴────┘
│ ├ capacity: 8 │ slots 0 to 4 hold a value, 5 to 7 hold garbage
│ └ growth: Double │
└───────────────────────┘
len says how many slots hold a value, counting from the beginning. capacity says how many slots the block of memory has. Nothing in memory itself marks the boundary between them. Slot 5 looks exactly like slot 4 to the computer; only len keeps track of which slots are real. Keeping len correct is core to this part of the project.
Asking for memory. We give you an allocator called MALLOC, which works like C's malloc and free from the October 19 lecture. It has two functions:
// Give me this many bytes. Returns a pointer to the first one.
unsafe fn malloc(bytes: usize) -> *mut u8
// Give back memory that malloc gave you. Pass the exact pointer malloc returned,
// and the whole block is freed.
unsafe fn free(ptr: *mut u8)
The only difference from C's malloc is that ours also writes down every allocation and free in a log, which the tests read to check your work.
malloc counts in bytes, and hands back a pointer to bytes, *mut u8. You want room for some number of Ts, so ask for the right number of bytes and then tell Rust what will live there, with as:
// Room for exactly one i32
let one: *mut i32 = unsafe { MALLOC.malloc(size_of::<i32>()) as *mut i32 };
// Room for n elements of type T, whatever T is
let many: *mut T = unsafe { MALLOC.malloc(size_of::<T>() * n) as *mut T };
// Finished with it
unsafe { MALLOC.free(many as *mut u8) };
size_of::<T>() is how many bytes one T takes. Never hard-code a size, since T could be anything.
Using the memory. There are three things you can do through a pointer, and the focus of checkpoints 2 and 3 is on these:
ptr::write(p, value)putsvalueatp. It overwrites whatever bytes were there without looking at themptr::read(p)moves the value atpout and hands it to you. Afterwards, treat that slot as empty&*pgives you a reference to the value atp, without moving it. The value stays where it is
Notice that 2 and 3 are basically move_out and get from checkpoint 1. The difference is that FixedSizeArray checked you were using them correctly, and nothing checks you now. These are the rules you have to keep yourself:
- Never read from a slot before you have written to it. Memory from
mallocholds whatever was there before, which is garbage - Never read from a slot twice without writing to it in between. After
ptr::read, the value belongs to whoever you handed it to. Reading it again makes a second copy of something there should only be one of, and both copies will try to clean up after themselves - Never write over a slot that still holds a value.
ptr::writedoes not clean up the old value first, so it is lost and never cleaned up
To get at slot i instead of the first slot, use p.add(i). It hands you a new pointer i elements further on, counting in elements and not bytes, since Rust knows how big a T is. It changes nothing in memory and does not change p. It is arithmetic on an address, the way i + 2 is arithmetic on a number, so you use the result right where you need it:
let p: *mut i32 = unsafe { MALLOC.malloc(size_of::<i32>() * 10) as *mut i32 };
unsafe {
// Write 33 into slot 2, the third element
ptr::write(p.add(2), 33);
// Look at it without moving it. You can do this as often as you like
let r: &i32 = &*p.add(2);
println!("{}", r); // 33
// Move it out. Slot 2 is empty again now
let v: i32 = ptr::read(p.add(2));
println!("{}", v); // 33
// What do you think this does? Slot 10 does not exist
// println!("{}", &*p.add(10));
MALLOC.free(p as *mut u8);
}
Every one of these operations is unsafe. That word does not switch Rust's rules off. It means you are signing your name to them: Rust cannot check this code, so you are promising that you did.
Open fast_vec/src/playground.rs and run it before you write anything:
cargo run --bin fast_playground
malloc_and_ptr() is a working example of all of this, and it prints the addresses it gets. The comments at the end ask what happens if you go past the end of a block, or read before writing. Try them!
What you are writing
Three things, in two files. The checkpoint 2 tests are in fast_vec/tests/cp2.rs.
1. next_capacity, in src/growth.rs. Doubling is not the only way to grow. Growth is an enum with three strategies:
Growth::Double: twice the old capacityGrowth::Multiply(factor): the old capacity timesfactor, rounded down. SoMultiply(1.5)grows by halfGrowth::Add(slots): the old capacity plus a fixed number of slots
next_capacity takes the current capacity and returns the new one. match on self to decide which rule applies. One requirement holds for every strategy: the answer must always be bigger than the capacity you were given, or push has nowhere to put the new element. Read that requirement carefully, and think about whether every strategy meets it for every capacity.
FastVec::new() uses Double. FastVec::with_growth(...) lets you pick, which you will need in checkpoint 3.
2. get, in src/lib.rs. Return a reference to the element at index i, using .add(i) and &*. You want to look at the element, not move it out, so that the caller can get it again later.
Before that, check the index. If i is not less than the length, there is no element there to return: the slot is either garbage or does not exist. Panic instead, with exactly this message:
panic!("FastVec: get out of bounds");
3. push, in src/lib.rs. Two cases, already set up for you in the stencil:
- There is room (length less than capacity). Write the element into the next empty slot, and update the length
- The vector is full. Ask
self.growthfor the new capacity. Allocate that much memory. Move every element from the old memory to the new, withptr::readfrom the old andptr::writeinto the new. Free the old memory. Then pointself.ptr_to_dataat the new memory, and update the capacity. Now there is room, so carry on as in the first case
Checklist
-
Merge checkpoint 1, pull
main, and make acheckpoint-2branch from it -
next_capacityworks for all three strategies.cargo test --test cp2 growth -
getworks, and panics out of bounds.cargo test --test cp2 get -
pushworks.cargo test --test cp2 push -
cargo test --test cp2is entirely green, seventeen tests -
cargo test --test cp1is still green -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Write
getfirst. Almost every other test uses it to check its answer, and so does printing aFastVecwithprintln! - Draw it. Boxes for slots, an arrow for the pointer, and a mark for which slots hold a value. Most bugs in this part of the project occur when a slot holds a value when you think it is empty, or the other way around
- When a test crashes instead of failing, the compiler cannot help you! Inside
unsafebugs happen that the compiler usually catches. To debug, rerun that one test by name instead of all at once. Printlen,capacity, andptr_to_data(with{:p}) before and after the step you suspect. Then check the three slot rules one at a time against your drawing. A crash inpushis often agetor a loop bound that is off by one somewhere earlier push_allocates_then_frees_the_oldchecks the order of what you do, by readingMALLOC's log. Allocate the new block before freeing the old one: you need both at once, to move from one to the other- Run
fast_memoryas you go. Case 1 pushes and removes; it will crash onremoveuntil checkpoint 3, so read what it printed up to that point - Copying the elements across one at a time is right. There are faster ways, but they are not the point here
- If your tests suddenly won't compile, check the playgrounds too!
Checkpoint 3: remove, clean up, and measure
FastVec can grow now. In this checkpoint you finish it, by teaching it to shrink and to clean up after itself, and then you find out whether all that work was worth it.
What you are writing
The tests are in fast_vec/tests/cp3.rs.
1. remove, in src/lib.rs. Remove the element at index i, and shift every element after it down one slot to close the gap. Unlike SlowVec, this needs no new memory: a FastVec holding [1, 3, 5, empty] becomes [1, 5, empty, empty], with the same capacity and one fewer element.
The removed element has to be cleaned up, so move it out with ptr::read first. Then, for every slot j after i, read its element out and write it into slot j - 1.
If i is not less than the length, panic with exactly this message:
panic!("FastVec: remove out of bounds");
2. Fix the bug in clear. We wrote clear for you, and it has a bug. It frees FastVec's memory, and on its own that looks right. Run this to see what it misses:
cargo run --bin fast_memory
Look at case 2. The Tracker says three values were never cleaned up, even though the memory is freed. Freeing memory throws away the bytes inside the vec itself, but it does not clean up the values that were in them (if they're heap types). For an i32 that makes no difference, but a String owns some heap memory of its own, and only the String itself knows to give it back. So before you free the block, every element in it has to be moved out and dropped. Which of the three pointer operations moves a value out?
3. Drop for FastVec. What happens to a FastVec when it goes out of scope?
Right now, nothing at all. Its memory came from MALLOC, and Rust has no idea it is there, so it never gets freed, and neither do the elements in it. Every FastVec your program has ever made has leaked.
SlowVec never had this problem. The third ownership rule in Rust says that when the owner of a value goes out of scope, the value is dropped, and that is what happened to each old FixedSizeArray in checkpoint 1. Dropping one runs some code that FixedSizeArray provides, which cleans up its elements and frees its memory. FastVec needs that code too, and now you'll write it. It goes where the comment YOUR Drop GOES HERE is in src/lib.rs, and has this shape:
impl<T> Drop for FastVec<T> {
fn drop(&mut self) {
// Runs automatically when a FastVec goes out of scope.
// Clean up every element, then free the memory.
}
}
You never call drop yourself! Implementing Drop for FastVec means Rust will call it for you at the end of the vector's scope. There's a function you can call here that already does the work, so the body is one line of code.
4. The timing functions, in src/timing.rs. time_fast_pushes and time_slow_pushes each push n elements, one at a time, and every every pushes record a sample: how many elements have been pushed so far, and how many milliseconds have passed since the first push. The comment at the top of the file describes them exactly, and shows how to use Instant, Rust's stopwatch.
time_fast_pushes is given the FastVec to push into, so that the benchmark can hand it vectors with different growth strategies. Make sure you push into that one.
5. Your growth experiments, in src/benchmark.rs. Once the timing tests pass, run the benchmark:
cargo run --release --bin benchmark
Use --release. It turns on the compiler's optimizations. Without them the benchmark takes much longer, and the timings mostly measure how slow unoptimized code is.
It writes two plots into the top folder of your repo. benchmark_slow.png races SlowVec against FastVec. benchmark_growth.png races growth strategies against each other, and so far it has only one: Double. Which others go on it is up to you, and this is where branches come in again.
Each idea you try gets its own branch. For example, to try out a few multipliers:
git switch -c growth-multiply
Then add the strategies you want to compare at YOUR CHOICES GO HERE in benchmark.rs, up to four lines on the plot in total. Each one looks like the Double line above it, with a different Growth and name:
series.push(("Multiply(1.5)", time_fast_pushes(FastVec::with_growth(Growth::Multiply(1.5)), n, every)));
Run the benchmark, look at the plot, and commit benchmark.rs and both plots on that branch. Push it with git push -u origin growth-multiply.
Then go back and try something else on a new branch:
git switch checkpoint-3
git switch -c growth-add
This is the other thing branches are for. If an experiment goes wrong, you can commit it anyway and switch back to a working branch. git switch checkpoint-3 puts everything back the way it was, and the broken attempt is still sitting on its own branch if you ever want to revisit it.
Make at least two experiment branches, each with a name that starts with growth-. Different strategies, different knob settings, a mix: your call. Then pick the one whose plot makes the best argument, and merge it into your checkpoint branch:
git switch checkpoint-3
git merge growth-multiply # or whatever branch you want to keep
That brings its benchmark.rs and plots along with it. Both plots have to be committed on main when you submit: the writeup is about them, and a missing plot costs points. Leave the other experiment branches unmerged, but pushed. They stay on GitHub as a record of what you tried, and we will look at them with you at code review.
6. The writeup, in the README of your repo. The questions are at the end of this page, and the headings are already in your README. They ask about your own plots, so you cannot answer them until your benchmark runs.
Checklist
-
Merge checkpoint 2, pull
main, and make acheckpoint-3branch from it -
removeworks, and panics out of bounds.cargo test --test cp3 remove -
cleardrops every element.cargo test --test cp3 clear -
FastVechas aDrop.cargo test --test cp3 dropping -
The timing functions work.
cargo test --test cp3 timing -
cargo testis entirely green, all three checkpoints -
At least two
growth-branches, each with a plot committed, pushed to GitHub. We check these with you at code review -
One of them merged into
checkpoint-3, so both plots end up onmain - The writeup is answered in your README
-
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Read the
cp3tests before you start. Their names say what they check:remove_never_allocates_or_freesandremove_drops_exactly_one_element - In
remove, the last element's old slot is empty afterwards. Nothing should read it again, and nothing will, as long as you update the length Dropruns on everyFastVec, including one that was already emptied byclearorinto_vec. Both of those leave the pointer null and the capacity at zero. Remember, freeing the same block twice is an issue- If a timing test says the times went down, you are probably restarting the stopwatch inside your loop
- If the benchmark seems to hang, check you used
--release.SlowVecgets slow fast, and debug mode makes it many times slower - A plot with one line that dwarfs the others hides the differences between the rest. If two strategies look identical, try putting them on a branch of their own or make them more distinct from each other
- If your tests suddenly won't compile, check the playgrounds too!
The writeup
Your writeup goes in the README of your repo, under the headings that are already there. Leave the rest of that file alone.
Two to three sentences per question, unless it says otherwise.
Reading the plots
1. SlowVec against FastVec. Look at benchmark_slow.png. Describe the shape of each curve. Why does SlowVec's bend upward? Write the total cost of n SlowVec pushes as a function of n. Hint: how many elements does the k-th push move?
2. Why push is fast on average. Some FastVec pushes copy the entire vector, and yet Double's curve is a straight line. Count the steps for 16 pushes, the way the table in checkpoint 2 does for 8. Then explain, in terms of how often resizes happen and how big they are, why the average cost per push stays the same however big n gets.
3. Your growth experiments. Which strategies and settings did you try, and on which branches? What did the plots show? Which branch did you merge, and why that one? Being fastest is not the only thing that matters: right after a resize, how much of each strategy's memory is empty?
4. Why Add eventually loses. Pick any fixed k. As n grows, Add(k) eventually loses to Double, even though a big enough k can win at one particular n. Why? What changes about the curve as k gets bigger, and what doesn't?
Memory
5. Two kinds of leak. The tests check for leaks in two ways: Tracker and MALLOC's log. What does each one catch that the other misses? Describe a Drop that would pass one check and fail the other.
6. The bug in clear. What was wrong, and how did you find it? Why could you not have written the same bug in SlowVec?
Process
7. What's something you tried that failed at first on this project, and how did you adapt?
Your AI citation. Who and what you used, and how. Course policy is in the syllabus.
Project 3: Tic Tac Toe
Welcome to your third project!
How do computers play strategy games like checkers or chess? They don't act intuitively like we might, they look ahead instead. For every move they could make, they imagine every move their opponent might make after, and every reply they could make to that, as far as they can imagine with the time and compute they have, and then they pick the move that works out the best regardless of the other player's decisions. That idea is called minimax, and with it a program can play any two-player game where both players can see the whole board. Checkers, chess, Go, Connect Four, and Tic Tac Toe.
In this project you will start by writing a Tic Tac Toe board (maybe a more interesting one than you're used to!), then an agent that plays it with minimax, then a tournament that plays agents against each other. On a 3x3 board your agent will be unbeatable, but on a 5x5 board with walls it can't look all the way to the end, so you'll have to work within a time limit and use heuristics in addition to the look-ahead strategy to make decisions. The quality of those heuristics will ultimately be what makes one agent better than another, and at the end of the semester we will pit every agent in the class against each other to declare a final winner!
This project starts alongside the traits unit in lecture. An Agent is itself a trait, your Minimax is one type that implements it, and the tournament holds agents of different types in one Vec<Box<dyn Agent>> (so we'll finally get to see what Boxes are really useful for too!).
What is due when
- Checkpoint 1, Friday November 13. The board with your tests of it
- Checkpoint 2, Friday November 20.
Minimaxon the 3x3 board - The project, Friday December 4. The 5x5 game, round robin, and your writeup
- The tournament. We run it on the agent you submit on December 4, and the results come out in the last lecture
- Code review, in discussion the week of December 7
Checkpoint 1 is smaller, since it falls the week after the midterm. Checkpoint 2 is the heart of the project. Nothing in the last part needs anything from lecture past Nov 20, so you can manage your own time after that.
Meet your project repo
Your starting point is https://github.com/rust4ds/ds210-fa26-project-3.
Same as before: on GitHub, click Use this template, then Create a new repository. Name it ds210-fa26-project-3 and set it to Private. Then clone it.
src/board.rs checkpoint 1. The board: moves, apply and undo, score, game over
src/minimax.rs checkpoints 2 and 3. Your agent
src/tournament.rs checkpoint 3. The round robin
tests/my_tests.rs checkpoint 1. Your tests of the board
src/bin/arena.rs checkpoint 3. A playground for pitting heuristics against each other
src/agent.rs the Agent trait, and four agents to play against
src/game.rs plays one game between two agents, with a clock
src/layout.rs starting boards: 3x3, 5x5, bigger, with or without walls
src/player.rs X and O
src/main.rs the command line tool
tests/cp1.rs, cp2.rs, cp3.rs the checkpoint tests
README.md instructions to start, and where your writeup goes
You will only edit the first five files, plus the writeup in README.md. The others are ours. You should read them to make sense of them, since your code calls them, but leave them alone: when your agent enters the tournament it has to compile against our copy of everything else.
Like usual, all the spots where you have to write code are marked todo!, with a comment above it that sketches the steps.
Working on branches
Same workflow as Project 2: each checkpoint on its own branch, merged into main with a pull request when its tests pass.
git switch -c checkpoint-1
The Project 2 page has the full set of commands if you want them again.
Running your project
Everything runs from the top folder of your repo:
cargo run -- human random # play: you against a random agent, 3x3
cargo run -- human minimax # play: you against your agent
cargo run -- minimax greedy --board walls # watch your agent play against Greedy, 5x5 with walls
cargo run -- random first --board open # watch two agents on 5x5, no walls
cargo run -- tournament --board walls # watch everyone against everyone, on six fixed boards
cargo run -- minimax greedy --board open --size 7 --depth 3 # a bigger board
cargo run --bin arena # your heuristics against each other (checkpoint 3)
The agents are first, random, greedy, human, and minimax. All of first, random, and greedy are programmed for you, human lets you decide moves in real time, and minimax is yours to code up.
The boards are classic (3x3, the default), open (5x5), and walls (5x5 with five walls in random places). --size N makes the open and walls boards bigger, --depth N limits how far minimax looks ahead, and --limit SECONDS changes the time limit per turn. cargo run -- --help lists all of it.
On a fresh clone of the template repo none of these will run, since you first need to complete the todo!-marked code and make the board.
Open the repo's top folder in VS Code, with code . from inside it, so that rust-analyzer finds Cargo.toml and gives you types and errors as you type.
Running the tests
cargo test --test cp1 # the board
cargo test --test my_tests # your tests of the board
cargo test --test cp2 # Minimax on 3x3
cargo test --test cp3 # 5x5, the heuristic, and the round robin
cargo test # all the tests
Add part of a test's name to run only the tests that match it: cargo test --test cp1 undo.
When you first clone your repo, every test fails and you'll see a lot of warnings about things that are declared and never used. That's expected until you start writing your code.
If a test hangs, your search is probably looking too far ahead. A full minimax search of a 5x5 board never finishes. Press Ctrl-C and fix the bug, and try running one test at a time.
The rules of the game
You are probably familiar with the 3x3 game. X goes first, players alternate, three in a row wins, and if the board fills up it's a draw.
The 5x5 game is a little different. A great way to learn about it is by running it with the human option and playing against the computer.
- Some cells are walls, drawn
#. Nobody can play there, and you can't make a three-in-a-row through a wall. - Three in a row scores a point, and the game continues. It ends when the board is full, and whoever has more points wins. Four in a row is two runs of three, so it scores two
- In the code, the score is X's runs minus O's runs. Positive means X is ahead, negative means O is, zero is a tie. On the 3x3 board the game ends the moment the score is anything other than 0
That one number, X minus O, runs through the whole project. X wants it big, and O wants it small (negative).
Submitting
As before, each checkpoint and the final project has its own Gradescope assignment, which asks you to log into GitHub and point it at your repo. Pick the main branch (making sure all your work is on main).
Checkpoint 1: The board
Everything else in this project is built on the board, so we need to build that first.
What you are given
Open src/board.rs. The types at the top are written for you:
Cellis an enum representing one square. It is eitherEmpty,Wall,X, orO.Cell::mark(player)gives the mark a player makesPositionis(row, col), both counted from zero at the top left. The line that defines it,pub type Position = (usize, usize);, makesPositiona type alias, which is new: a second name for a type that already exists. Unlike a tuple struct, which you have seen, it makes no new type. A plain(1, 2)already is aPosition, and you take one apart the way you would any tuple, withlet (row, col) = position;. The alias is there so a function signature can sayPosition, where(usize, usize)would be less clearBoardhas three fields:cells, aVec<Vec<Cell>>so thatcells[row][col]is one square;to_move, whose turn it is; andhistory, aVec<Position>of every move made so far, in order
Some methods are written too. size() is the number of rows, which is also the number of columns. cell(row, col) reads one square. to_move() says whose turn it is. And Board::from_rows builds a board from text, which you will use constantly:
let board = Board::from_rows(&["XX.", ".O.", "..#"]);
X and O are marks, # is a wall, and anything else is empty. X is to move unless X already has more marks than O. The starting boards in src/layout.rs are built the same way.
What you are writing
Five methods, each marked todo!:
moves()returns every empty position, top to bottom and left to right. These are the legal movesapply_move(position)puts the current player's mark there, records the move inhistory, and makes it the other player's turn. If the cell isn't empty, it panics, with a message that includes the wordillegal.undo()takes back the last move: everythingapply_movedid, backwards. It panics withnothing to undoif there's nothing to take backscore()counts the runs of three. Every run of X's is plus one, every run of O's is minus oneis_over()says whether the game is finished: no moves left on any board, or three in a row on the 3x3 board
Notice what history is for. Minimax will try a move, look at what happens, then take it back and try the next one, thousands of times. apply_move pushes onto the end of history and undo pops off the end, so the last move in is the first one out. That shape should be familiar (it's a stack!) and we'll see it more deeply in lecture soon.
score() is the most involved method to write. Every three-in-a-row has a first cell, and from there it goes in one of four directions: right, down, down-right, or down-left. Left and up would wind up double-counting the same runs. So for every cell on the board, look in each of the four directions, skip any direction where the third cell would fall off the board, and check whether all three cells hold the same mark. Rows and columns are usize, so the down-left direction needs care: a usize can't go below zero, and asking it to panics.
Your tests
tests/my_tests.rs has one example test on score and room for yours. Write at least three more.
What makes a test worth writing? Think about how score could be broken. A score that forgets one of the four directions would pass a test on rows and columns. One that only checks the first three cells of a row passes on a 3x3 board and misses runs on a 5x5. One that stops at the first run it finds gets a four-in-a-row wrong. Build a position with Board::from_rows where exactly one of those mistakes would show, and assert the right answer. The tests we wrote in cp1.rs are the same idea, and reading them is a good way to see what yours could add.
We will run your tests against boards we broke on purpose, after the deadline. A test that catches the breaks earns credit!
Checklist
- Make your own private copy of the Project 3 repository with Use this template, then clone it
-
Put your name and your GitHub username on the two lines at the top of
README.md -
Make a
checkpoint-1branch -
The five board methods work, and
cargo test --test cp1is entirely green, twenty-six tests -
At least three tests of your own in
tests/my_tests.rs, and they pass -
cargo run -- human randomlets you play a game -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- Remember you can run a subset of tests by name, so
cargo test --test cp1 movesruns only the tests ofmoves BoardhasPartialEq, so a test can compare two whole boards withassert_eq!. Theundotests do exactly that: apply, undo, and check the board is what it was- Each of the four directions in
scoreis a pair of steps: how much the row and the column change for each cell along the run. Right is(0, 1), down is(1, 0), down-right is(1, 1), and down-left is(1, -1). Put the four pairs in an array and loop over it, and the three cells of a run are(row, col),(row + step_row, col + step_col), and(row + 2 * step_row, col + 2 * step_col). That lets you write one loop instead of four - Two catches with the steps. They can be negative, so they can't be
usize: do the arithmetic inisize, check the result is on the board, and only then convert back withas usizeto index intocells(or check when you've hit zero before subtracting). And Rust won't add two tuples for you, so(row, col) + (step_row, step_col)doesn't compile; you'll need to add the two parts separately - Play a few games against
randomonce the board works. You'll noticehumanmoves aren't timed, and the board prints its row and column numbers so you can type a move as two numbers
Checkpoint 2: Minimax
How to think ahead
Here is a 3x3 position with X to move:
X | O | X
---+---+---
| O |
---+---+---
| |
X has four choices. Suppose X plays bottom left. Then O has three choices, and one of them, bottom middle, wins the game for O. So "bottom left" is a bad move for X, because of what O can do later.
Minimax expands on this lesson. Think of every position as a node in a tree, with the current board at the root and one child for every legal move. At the bottom of the tree are finished games, and a finished game has a score: the board's score(), positive if X won. Now we can give every unfinished node a score too, working upward. At a node where it's X's turn, X will pick the child with the biggest score, so that's the node's score. At a node where it's O's turn, O picks the smallest. If we continue backwards, the score that ends up at the root will be how the game ends if both players play perfectly.
X maximizes, O minimizes, hence the name "minimax". Both players are playing the same game with the same information, they just want the score to go opposite ways.
Two things to notice. 1) The algorithm is recursive, since the score of a node is a function of the scores of its children, and the base case is a finished game whose score is obvious. 2) The strategy never has "intuitions" about the game: it doesn't know that the center is a good square, or to try to trap the opponent between two bad moves. It's just simulating and accounting.
What you are given
src/agent.rs has the Agent trait:
pub trait Agent {
fn name(&self) -> String;
fn choose_move(&self, board: &Board, time_limit: Duration) -> Position;
}
An agent is anything that can look at a board and pick a move. The move has to be one of board.moves(), and it has to come back inside the time limit, or the game is forfeited. Four agents are written for you: FirstMove plays the first legal move it finds, Random picks one at random, Greedy tries every move and keeps the one that makes the score best right now, and Human asks you interactively. It may help to read Greedy, as it's similar to the loop you're about to write, without the recursion.
The trait has one more method, is_human, with a default that returns false. Human overrides it so that a person at the keyboard isn't on the clock. Leave it alone in your own agent. The tournament checks for it, and an entry that overrides it is out.
src/game.rs has play_game, which runs one game between two agents, times every move, and reports who won. It takes its two agents as &dyn Agent. This means play_game works for any two agents, of any two types, as long as they implement the trait. We'll come back to that in checkpoint 3.
src/minimax.rs has the Minimax struct, which is yours to write. It has three fields: max_depth (how far to look ahead), label (what it calls itself), and heuristic (the function it uses to guess at a position it didn't finish searching). Three constructors fill them in. Minimax::new() searches to the end of the game, Minimax::with_depth(d) stops after d moves and guesses, and Minimax::with_heuristic(d, name, f) lets you choose the guessing function too. Checkpoint 2 only asks you to write out Minimax::new().
What you are writing
Two functions in src/minimax.rs:
search(&self, board: &mut Board, depth: usize) -> i32is the recursion step. It returns the score the next player can get if they move optimally from this position:- If the game is over, that's just
board.score(). - If
depthis zero, the agent is left to make an assumption using(self.heuristic)(board), which by default returns the score at that point. (The first pair of parentheses picks out the function stored in the field; the second pair calls it. Without the first pair Rust looks for a method namedheuristic, and there isn't one.) - If
depthis positive, it looks at every available move, applies it, callssearchwith one less depth, undoes, and keeps the best (the biggest result if X is to move or the smallest if O is next)
- If the game is over, that's just
choose_movewrapssearchso that it remembers which move gave the best score, and returns that as the next move
A few things for you to work out:
- Whose turn is it?
board.to_move()always knows, at every level of the recursion. Remember that X maximizes and O minimizes, so compare scores accordingly. If you write the recursion assuming your agent is always X, it will play well as X and lose as O - Clone or undo?
choose_moveis given&Board, which is an immutable reference, so it can't change it. So you'll need to clone it once to get a board of your own. Inside the loop you have a choice: either clone the board again before each move, or (with it mutable) apply the move, search, and undo it. Either will work, though one of them is slower and uses more memory (do you know which?) - Starting depth.
choose_moveapplies one move itself before callingsearch, so that move is the first level of the search and the call isself.search(&mut board, self.max_depth - 1). The constructors won't allow you to start with a depth of zero, so this subtraction is always safe. (A depth of one looks at each legal move and nothing further, which withscore_onlyis exactly whatGreedydoes! TryMinimax::with_heuristic(1, "greedy again", score_only)in the arena later and see if you can tell them apart)
Testing it
Play it. cargo run -- human minimax and cargo run -- minimax human, so you're O in one and X in the other. You should never be able to beat it. If you do, that game is a bug report: write down the moves.
Then the tests. cargo test --test cp2 tactics sets up six positions by hand and checks the move your agent picks: take a win when there is one, block when there isn't, as X and as O. cargo test --test cp2 games plays full games against FirstMove and Greedy, both colors, and expects a win each time, then twenty games against Random each way and expects you never to lose. Last, it plays your agent against itself and expects a draw, which is what perfect 3x3 play looks like.
After the deadline we also play you against an agent that isn't in your repo. It uses minimax too, so it never loses either; the tests check that you don't.
Checklist
-
Make a
checkpoint-2branch frommain -
searchandchoose_movework, andcargo test --test cp2all pass -
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- If a tactics test fails, the position is right there in the test, and you can build it in
main.rswithBoard::from_rowsand print what your agent does - A
gamestest that fails prints the final board. Look at where your agent was when it went wrong, then set that position up by hand - If
never_loses_to_randomfails once in a while and the others pass, you have a bug that only shows up on some move orders - Full search from an empty 3x3 board visits about half a million positions and should take well under a second. If it takes much longer, see if you can clone less and undo more
Checkpoint 3: The 5x5 game, and the tournament
Why the 3x3 agent can't play 5x5
Try it (and be ready to kill it):
cargo run -- minimax greedy --board open --depth 100
Nothing happens for a very long time. An empty 5x5 board has 25 legal moves, then 24 next moves, then 23, and the tree has about 25! leaves, which is a number with 26 digits. Checkpoint 1's score() on each would take... longer than the universe has been around. The depth limit is how every game-playing program handles this, in small projects like ours up to chess engines. You just get to look ahead a fixed number of moves, and at that point guess how the game will go instead of playing it out any further.
If we only look four moves ahead, the tree from an empty 5x5 board has 25x24x23x22 = 303,600 leaves, which takes about a quarter of a second. Five moves ahead is 21 times more, and it doesn't fit in the one-second limit, at least with the search as you've written it. So we'll be working with a 4-step look-ahead for most of the rest of the project.
The heuristic
With Minimax::with_depth(4), your search already stops at depth zero and calls the agent's heuristic. For new() and with_depth() that is the function my_heuristic in minimax.rs, which in the template just returns board.score(), which is the current net score (who is ahead right now). That's a decent guess, and you can try it against Greedy a few times:
cargo run -- minimax greedy --board walls
cargo run -- greedy minimax --board walls
It wins most of the time, and it also draws some and loses some, because it's not doing a great job of evaluating what might happen later in the game. Two X's in a row with an empty third cell count for nothing in this strategy, even though they're about to earn a point. Your job now is to make heuristic smarter. Keep it in the same units as score() (positive for X and negative for O), so the search can compare a guess with a real finished game, and think about what makes a position promising. Some ideas:
- Two in a row with the third cell empty, for either player
- Whether a cell is in many possible open lines (not blocked by walls) or few
- Whether it's early or late in the game. Potential matters more early, while points matter more late
The tests ask for a heuristic that never loses to Greedy on the six standard boards, as X and as O, and wins at least ten of those twelve games. The stencil's score() wins nine, draws two and loses one. One more test, heuristic_sees_more_than_score, gives your heuristic two positions that score() can't tell apart and asks which is better for X.
Measuring a heuristic
Beyond the tests, the measure of a heuristic is whether an agent using it beats an agent that doesn't. You can experiment with this: Minimax::with_heuristic(depth, name, function) builds an agent out of any function with the signature fn(&Board) -> i32, so you can pit two versions of your heuristics against each other in a tournament:
Box::new(Minimax::with_heuristic(4, "score only", score_only)),
Box::new(Minimax::with_heuristic(4, "open twos", open_twos)),
Passing a function by name, without calling it, is new. Parentheses are what call a function, so open_twos on its own is the function itself, handed over as a value for Minimax to store and call later. We'll see a lot more of this in the iterators lecture.
src/bin/arena.rs is set up to help you do this. It's a playground like the ones in Project 2: yours to edit, and not graded. It builds a Vec<Box<dyn Agent>> out of Greedy and four Minimax variants, two heuristics at two depths, and runs them through your round_robin on the six standard boards:
cargo run --bin arena
Add your versions, change the depths, swap in layout::sized(7). The writeup asks you to run this experiment with your own heuristic and report what you find.
Getting creative with the time limit
Every turn a player has one second to move. An agent that runs over forfeits the game, so a search that's too deep will always lose. Depth 4 fits comfortably, but depth 5 doesn't.
If you want to try for more depth, and in the tournament more depth is a real advantage, the trick is to skip the parts of the tree that can't change the answer, so the same second buys more depth. You can look up alpha-beta pruning, which is a well-documented algorithm, and try to implement it if you'd like. But it isn't required for the project.
Your agent can also see the time limit, so you could always search deeper when the board is nearly full and there are fewer moves to consider to make the best use of your one second, and search shallower when the board is empty. You're also not required to try that.
The round robin
This is the part that needs dyn. Open src/tournament.rs. Standing represents the results for one agent in the final results table. You need to fill in the round_robin function:
pub fn round_robin(agents: &[Box<dyn Agent>], boards: &[Board], time_limit: Duration) -> Vec<Standing>
Every agent plays every other agent, on every starting board, once as X and once as O. The standings come back sorted, most points first, three for a win and one for a draw.
Look at the type of agents. Remember from lecture why it can't be Vec<Agent>, or Vec<dyn Agent>: the agents are different types, and different sizes, so each one has to live on the heap behind a Box, and the Vec holds the boxes.
To hand an agent to play_game, which wants a &dyn Agent, write &*agents[i]: the * follows the pointer into the box, and the & borrows what's there (without the box).
cargo run -- tournament --board walls runs your round robin with FirstMove, Random, Greedy, and your Minimax on six fixed boards, and prints the table. Your agent should be at the top!
Entering the class tournament
Every agent submitted by the December 4 deadline is entered automatically. We take the src/minimax.rs from your Gradescope submission and play it against everyone else's, so there's nothing separate to hand in. Two things to set before you submit:
- Name your agent. This is what it will be called in the standings, so pick something you'd be happy to see at the top :-) Letters, digits, and underscores only, up to 20 characters. Write it on the Agent name line at the top of your
README.md, and set theAGENT_NAMEconstant at the top ofsrc/minimax.rsto the same thing. EveryMinimaxyou build takes itsname()from that constant - Pick your depth. Add a line to the top of your
README.md, right under the agent name, with the depth you want your agent to play at:**Tournament depth:** 4. More depth sees further, but your agent still has to move within the time limit. If the line is missing, we'll use 4
Three rules that make this work:
- Your
minimax.rsplays on ourboard.rs, so it can only call the board functions that came with the project. If it uses a helper you added to your ownboard.rs, move that helper intominimax.rs, or your agent won't compile and will have to sit out. - If you submit in the 48-hour late window, your agent has to sit out the tournament.
- And
is_humanhas to stay as it is (false).
The tournament runs in rounds, with the same one-second limit as your tests. Every entry plays every other on two of the standard boards, both colors, and the top half goes on. Those play again on four boards, and the top quarter goes on to a final round on all six standard boards plus six new boards with walls, so an agent that only learned the standard boards might not succeed. We'll share the results in the last lecture, round by round. Your rank doesn't affect your grade.
Checklist
-
Make a
checkpoint-3branch frommain -
my_heuristicsees more thanscore(), andMinimax::with_depth(4)never loses toGreedyon the standard boards and wins at least ten of the twelve games -
round_robinworks, andcargo test --test cp3is entirely green, eleven tests -
cargo run -- tournament --board wallsputs your agent at the top, andcargo run --bin arenahas your heuristic beatingscore_only -
Your agent name is on the Agent name line of
README.mdand inAGENT_NAME, your GitHub username is on its line, and you've added a Tournament depth line if you want something other than 4 - The writeup is done
-
Push the branch, open a pull request into
main, and merge it - Submit your repo on Gradescope
Hints and tips
- The cp3 tests play six games each way against
Greedywith a one-second limit, and if a move runs over, the failure message says how slow your slowest move was. A lost game prints which board it was on, andlayout::walls_seeded(5, seed)with seeds 1 to 6 rebuilds the standard boards if you want to replay one - If
cargo test --test cp3hangs rather than failing, a test is running your agent with a depth it can't finish - To compare two heuristics, keep the old one as a second function and put both in the arena
standings.sort_by(...)with a closure orsort_by_keywill both help sort standings
The writeup
Your writeup goes in the README of your repo, under the headings that are already there. Leave the rest of that file alone.
Two to three sentences per question, unless it says otherwise. The answers have to be in your own words. You can use AI to help you understand a question, but not to write the answer, and the code review opens with your writeup, so be ready to say more about anything you wrote.
1. Clone or undo. In search, did you clone the board before each move, or apply the move and undo it? What does the other choice cost, in memory or in time?
2. One trait, many agents. FirstMove, Random, Greedy, and Minimax are four structs that each implement Agent. We could have written one Agent struct with a kind enum and a match inside choose_move. What would be harder about adding a classmate's agent to the tournament under that design? What would be easier?
3. Why Vec<Box<dyn Agent>>. In your own words: why won't Vec<Agent> compile, why won't Vec<dyn Agent>, and what does the Box fix?
4. How big is the tree. Run your agent against Greedy on open boards of size 5 and 7, at depths 2, 3 and 4, and note the slowest move time each game reports: cargo run -- minimax greedy --board open --size 7 --depth 3. Put the six times in a table. Then explain them: how many leaves does the search visit from an empty n by n board at depth d, and what happens to that count when n goes from 5 to 7 at the same depth, or d goes up by one? If heuristic looks at every cell in every direction, roughly how much work is one move, in big-O terms, as a function of n and d?
5. Your heuristic. What does it reward, and why did you think that would matter? Then the experiment: run the arena with score_only and your heuristic at two depths each, paste the standings, and explain them. Which mattered more, the heuristic or the depth? Did anything surprise you?
6. Process. What did you try first that you ended up changing, and why? Name a specific commit where you made that change. If you had another week, what would you do to improve your agent?
Your AI citation. Required. Which tools you used, for what parts of the project, and how. If you didn't use AI at all, say that; an empty section reads as a missing one. Course policy is in the syllabus.
Discussion Sections
Discussion sections meet for 50 minutes each week. A sections (A2, A3, A4) meet Wednesday afternoons. B sections (B2, B3, B4) meet Tuesdays. (B3 and B4 meet with extended time on code review weeks.)
Discussions are used four ways:
- Content review and practice, reinforcing the week's lecture material
- Project code reviews in the week after each project deadline
- Proctored exam corrections about two weeks after each midterm
- Standalone practice sessions during the two weeks when only one set of sections meets
Discussion 1: Setup
Tue Sep 8 (B sections) / Wed Sep 9 (A sections)
By the end of today you should have five things working and talking to each other:
- A terminal to run commands in
- A GitHub account, so you have somewhere to submit work
- VS Code with rust-analyzer, for editing and debugging
- Git, so you can track your work
- Rust, so you can compile and run a program
You should go step-by-step. On Macs the first step starts a download that blocks steps 4+5, but you can work on 2+3 in the meantime.
1. Terminal
The terminal is where you type commands instead of clicking. Everything else today gets installed and checked from here. This step is different depending on your machine, so find your part below.
On Mac
The Terminal app comes built-in on Mac. Press Cmd+Space, type Terminal, and press Enter. You can also find it in Applications, then Utilities.
Check it works by typing this and pressing Enter:
pwd
It prints the folder you are currently in. If you get a path back, you have a working terminal.
Now start installing Homebrew, which is a helpful utility for installing other applications (that you'll probably find yourself using a lot in the future). Run this line:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Three things to know before you start it:
- It asks for your Mac password in the first minute so keep an eye on it. Nothing appears on screen as you type the password, which is normal
- It may install Apple's command line developer tools if you don't have them yet.
- When it finishes it prints a "Next steps" list with some commands in it. Go ahead and run them! These put
brewon your PATH so that your shell can find it in the future.
Check it worked:
brew --version
While it's downloading, you can continue to the next step. Just press Cmd+N to start a second Terminal window (and now you know you can have more than one at a time!)
On Windows
Before you install anything, you will need to know if your machine uses x64 or ARM. If you're not sure, you can look in Settings > About > Device Info where you should see "System Type" indicates x64 or ARM.
Install Git for Windows from git-scm.com/download/win, taking the default options. That gives you a program called Git Bash, which is the terminal we will use all semester. It behaves the way Mac and Linux terminals do, so the commands in class will work on your machine. It also installs git, which is step 4, so you get both at once.
Use Git Bash, not PowerShell or Command Prompt, whenever these instructions say "terminal", even if you have the others installed.
Check it works by typing this and pressing Enter:
pwd
It prints the folder you are currently in. If you get a path back, you have a working terminal (and as a bonus, with Git Bash you already have git).
2. GitHub account
Create an account if you do not have one, at https://github.com.
You can use either your personal email address or your BU one. You will want to keep this account after you graduate. You may also want to use a professional-sounding name, not a silly one, since this can become a public presence and part of your resume / professional portfolio. But you're all adults, and we don't care ourselves if you name it after a pokemon.
You will fork your first repository in Lecture 4 on Friday, and Project 1 is submitted by pasting the URL of your fork into Gradescope. So the account has to exist and you have to be able to log in.
Turn on two-factor authentication while you are here. If you don't do it now you'll be forced to when you're in the middle of something later and you will be annoyed.
3. VS Code
VS Code is a free code editor. Install it from code.visualstudio.com, taking the default options. If you are passionate about a different IDE already feel free to use it.
Install the rust-analyzer extension
This is what makes VS Code understand Rust, so it can color the text and detect possible errors before the code compiles or runs.
- Open VS Code
- Open the Extensions panel: the icon of four squares in the left-hand bar, or Ctrl+Shift+X (Cmd+Shift+X on Mac)
- Search for rust-analyzer
- Install the one published by The Rust Programming Language, not a lookalike
Turn on autosave
VS Code does not save your file when you click over to the terminal. Git only ever sees what is saved, so an unsaved file is invisible to it. Without autosave, you might make a change to a file, try to commit it, and get confused by the responses that there's nothing to commit. So let's do this:
- Open the File menu
- Click Auto Save
A check appears beside it once it is on, and from then on VS Code saves your changes about a second after you stop typing.
Turn on the code command: Mac only
This lets you type code . in a terminal to open the folder you are standing in. You will use it all semester. (The VS Code installer already set this up for Windows users.)
From VS Code:
- Press Cmd+Shift+P to open the Command Palette
- Type
shell command - Click Shell Command: Install 'code' command in PATH
- Give it your Mac password if it asks
To test, close your terminal, open a new one, and run:
code --version
Make VS Code's terminal Git Bash: Windows only
VS Code has a terminal built into it, and on Windows it opens PowerShell, not Git Bash, by default. We want it to use Git Bash instead. (The default for Mac users is already what we want.)
From VS Code:
- Press Ctrl+Shift+P to open the Command Palette
- Type
default profile - Run Terminal: Select Default Profile
- Choose Git Bash
If a terminal was already open, close it with the trash can icon and open a new one. The change only affects terminals opened afterwards.
4. Git
You now almost certainly have git already. Windows users installed it in step 1 along with Git Bash. Mac users got it from the developer tools that Homebrew installed. So this step is mostly configuration.
Check:
git --version
If this prompts you to install the Xcode command line tools, say yes and let it finish. That means Homebrew has not got there yet, so give it a minute.
Then tell git who you are. This gets attached to every commit you make, so use your real name and the email address you use for your GitHub account:
git config --global user.name "Your Full Name"
git config --global user.email "your.email@example.com"
git config --global init.defaultBranch main
Check it was saved:
git config --global user.name
5. Rust
Install Rust from: https://www.rust-lang.org/tools/install
For this you will have to use the terminal. Once you enter the command that the website provides, choose the default option.
On Windows only, the site will point you to also install Visual Studio and C++ development packages inside it. You'll want to select the option called "Desktop development with C++".
When you run the installer, your computer might "protect" you by preventing the installer from running.
- On Windows, you can get around this by clicking on "more info" and then "run anyway".
- On Mac, you can try right-click (or Control-click) to see "Open", or after you tried to open the installer and couldn't, go to Settings > "Privacy & Security" and you might see a note there that the installer was blocked and there's a button there to click called "Open Anyway".
The installer might take some time, especially on Windows to install the C++ dependencies. In the meantime, you can get started with Step 6.
Check that it worked
Run this in your terminal (Terminal on Mac, Git Bash on Windows):
cargo --version
You should see a version number, 1.97.0 or later.
Now we'll build and run something. Navigate to a folder of your choosing, say your desktop (cd ~/Desktop or similar) before continuing. (Especially for Windows users, as the default starting location in Git Bash is not where you want to save things.)
# cd into where you want to build your project
cargo new hello_world
cd hello_world
cargo run
If it worked, you will see:
Hello, world!

Troubleshooting common issues on Windows
"cargo: command not found" or "not recognized"
Rust installed, but your shell does not know where to look. Add %USERPROFILE%\.cargo\bin to your PATH environment variable.
For help editing your PATH, see youtube.com/watch?v=gb9e3m98avk for an example showing how to edit your PATH to add a python directory - don't copy the python path exactly, but add %USERPROFILE%\.cargo\bin instead.
It compiles nothing, and mentions link.exe
You are missing the C++ build tools, which include the linker Rust needs. Install the Windows SDK and the MSVC C++ Build Tools from https://visualstudio.microsoft.com/downloads/, choosing the latest version compatible with your machine.
This one is a large download and will not finish in this session. Talk to a TA, start the download, and you are covered for today's attendance.
Rust seems installed but fails when it runs
You may be missing Microsoft's Visual C++ redistributable package. Install it from https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170.
6. Connect your computer to GitHub
Install the GitHub CLI
This is the way we recommend, and it is what GitHub's own documentation recommends.
On Mac once Homebrew is done installing:
brew install gh
On Windows, it does not come with Git Bash, so install it. If you have winget, which ships with Windows 10 and 11, this is the fast way:
winget install --id GitHub.cli
Otherwise download it from cli.github.com and take the default options.
Either way, close Git Bash and open it again afterwards. A terminal that was already open will not know the new command exists.
Then, on either machine:
gh auth login
Answer the prompts:
- GitHub.com, not an enterprise server
- HTTPS as the protocol
- Yes when it asks whether to authenticate Git with your GitHub credentials. This is the step that matters, so do not skip it
- Login with a web browser, then copy the one-time code it shows you and paste it into the browser window that opens
Check it worked:
gh auth status
You should see that you are logged in to github.com as your username.
If you would rather not install the CLI
Git Credential Manager also works and needs no setup on Windows, where it is installed along with Git Bash. The first time you push, a browser window opens, you log in once, and it remembers you after that. On Mac you can install it with Homebrew if you have it: brew install --cask git-credential-manager.
SSH keys are a last resort. They work, and you may see them recommended in older tutorials, but they are more setup and more to go wrong. Only use them if both options above have failed you, which should not happen. GitHub's guide is here if you need it, and please tell a TA if you end up going this route.
7. Putting it all together
Everything above was installed separately. This is the check that the pieces talk to each other, and it is what you show your TA before you leave.
Open your toy project in VS Code
Use File, then Open Folder. Do not use Open File, since Rust tooling needs the whole project folder, not one file. (These screenshots are taken on a Mac, and things might be a bit different for Windows users.)

Choose the hello_world folder you made in step 5, and press Open.

You should now see the project in the sidebar. Open src, then main.rs.

Check Rust and rust-analyzer
Replace the contents of main.rs with this:
fn main() { let x = 10; let y = 15; let sum = 10 + 15; println!("{x} + {y} = {sum}"); }
Two things should happen, and both mean rust-analyzer is running:
- Greyed-out type labels appear next to your variables, showing
: i32, even though you did not type them - A small Run | Debug line appears just above
fn main(). Click Run, and the output shows up in a panel at the bottom

If you see 10 + 15 = 25 at the bottom, Rust and rust-analyzer are both working.
If rust-analyzer isn't working yet you may need to add the folder as a trusted workspace. Try hovering over rust-analyzer in the bottom of VS Code and click "reload workspace" which will prompt you to add the project as a trusted workspace. You may need to reload workspace a second time after that to get code highlighting and the run button to appear.
Check git, without leaving VS Code
VS Code has a terminal built into it, and it opens already sitting in your project folder. Press Control and the backtick key together (top left of the keyboard, under Escape) to show it. This is Control on Windows and on Mac, not Command.
On Windows this should say Git Bash, because you set that in step 3. If it says PowerShell, go back and set the default profile.
Then run:
git status
You should see On branch main, No commits yet, and a short list of untracked files.
That branch exists because cargo new quietly turned this folder into a git repository when you created it. You did not ask it to. What that means is Friday's lecture.
Show your TA
Three things, all on one screen:
- The greyed-out
: i32type hints 10 + 15 = 25in the output- Your
git statusoutput in the built-in terminal
They'll mark your work as complete for the day.
If you weren't able to finish, that is fine and it is why we are here. Talk to your TA about what is going wrong and make a plan for finishing by Friday. You get the credit for showing up and having the conversation, not for a perfect machine.
8. If you finish early
Make the terminal your own
Your shell reads a configuration file every time it starts, and anything you put there is waiting for you in every future session. Aliases let you make short names for things you type constantly.
alias ll='ls -la'
alias ..='cd ..'
The appendix to Lecture 2 walks through this, including which file to edit on your platform.
Discussion 2: Git Skill Practice
Tue Sep 15 (B sections) / Wed Sep 16 (A sections)
Today you and a partner collaborate on a single repo. You will create branches, merge them two different ways, collide with each other on purpose, and come to a resolution.
You have done all the individual pieces already in class: fork, clone, commit, push. This time you'll see what happens when multiple people are trying to do this at the same time.
Work in pairs if you can. If your section has an odd number, talk to your TA to make a plan.
Part 1: One repository, two people
Decide which of you will be "Person A" and which will be "Person B" for the rest of this exercise. Then follow these steps:
-
A goes to https://github.com/rust4ds/ds210-git-practice and clicks Use this template, then Create a new repository. Name it whatever you like and make it public.
-
A opens the new repo's Settings, then Collaborators, then Add people, and adds B by their GitHub username.
-
B accepts the invitation (it arrives by email and/or by notification on github.com depending on your settings).
-
Both of you clone the repo. It is A's repo, so you both use A's URL:
git clone <A's repo URL> cd <the folder it made> cargo run
You should both see the same crew with nobody on it.
-
Both of you run these two lines in your terminal. You'll never have to do these again:
git config --global pull.rebase false git config --global core.editor nano
The first tells git pull to combine work by merging, which is what we have taught you. Without it, you'll have issues with git pull.
The second means that when git needs you to write something, you get nano, which you have used, instead of vi, which you have not (and which is much harder to use).
Both of these options will also be helpful for you for Project 1.
Part 2: A branch you merge yourself
In this part, you'll create a new branch, edit it, and try to send your edits up to your shared repo. Whoever does it first will be fine, but whoever gets there second will have to face the fact that your versions have diverged.
Both of you, around the same time, create a new branch by running:
git checkout -b <your-name>-notes
Make a new file called <your-name>.md and write a sentence in it. Then you'll commit your change to your branch, switch back to main, merge your change into main, and push the updated main back up to GitHub:
git add <your-name>.md # or git add .
git commit -m "Add <your name>'s notes"
git checkout main
git merge <your-name>-notes
git push
The second person who gets there will get an error on that last line. Read it. Git is telling you the other person got there first and you do not have their commit yet. Do what it says:
git pull
git push
Two things to expect from that pull. If it complains about "divergent branches", you skipped step 5 of Part 1: run it and pull again. And when it works, an editor opens with a commit message git has already written for you. You do not have to change it. Save and close, which
in nano is Ctrl+X and then Y and the merge finishes.
Check in with each other about what just happened. That pull merged your partner's work into yours and you didn't have to do much to fix the issue. Since you edited different files, git was smart enough to combine the edits without your involvement. Let's make it more interesting...
Part 3: A conflict on your own machine
Same idea, but this time you will edit the same line.
From main (run git status to make sure you're on the main branch still), without telling each other what you are typing, open src/main.rs and change MOTTO to a motto you like. Then:
git add .
git commit -m "Add our motto"
git push
One of you pushes fine. The other is rejected again, so pull like last time:
git pull
This time the pull does not go quietly. Git says CONFLICT (content): Merge conflict in src/main.rs and stops in the middle of the merge. Open the file:
<<<<<<< HEAD
const MOTTO: &str = "Measure twice, push once";
=======
const MOTTO: &str = "Ship it and see";
>>>>>>> 0cf7a8d
Above ======= is what you wrote. Below it is what arrived from GitHub. The letters and numbers at the end is the commit ID ("hash") it came from.
For fun, before you fix the conflict, go ahead and run
cargo run
It won't compile and the compiler says error: encountered diff marker and tells you where. Which is a helpful reminder that we still need to fix this!
You now need to "resolve" the conflict by picking which motto to keep (or creatively combine them), delete all three marker lines, and check your work again with cargo run to make sure it compiles.
Then finish the merge and push:
git add .
git commit -m "Merge mottos"
git push
Remember this moment - something like this is going to come up during Project 1!
Part 4: A branch that goes through a pull request
In Part 2 you merged one branch into another locally by running git merge branch-name from the branch you wanted to merge into. This time we'll see how merging works in GitHub, where you might want to ask your collaborators for feedback or permission before you merge into a critical or even production/operating version of your code.
Both of you:
git checkout main
git pull
git checkout -b <your-name>-crew
Make these two edits, and only these:
-
In
src/main.rs, changeCREW_NAMEto a crew/team name you like. -
In
src/main.rs, replace the(nobody has signed on yet)line with one for yourself like:#![allow(unused)] fn main() { println!(" - Your Name"); } -
In
README.md, fill in the crew name under## Crew nameand put yourself under## Members.
Then commit and push the branch itself to github:
git add .
git commit -m "Name the crew and sign on"
git push -u origin <your-name>-crew
git push -u origin branch-name sets up the link between your local branch and GitHub, and is only needed the first time you push after creating the branch. If you update your branch further all you'll need to do in the future to track it is run git push.
Now both of you go to GitHub, and you should both see a banner offering to open a pull request. (If you don't see the banner, you can create a Pull Request by going to the Pull Requests tab, then "New Pull Request" and setting "base" to main and "compare" to your own branch.)
In the right-hand sidebar, under Reviewers, request your partner by their GitHub name (since they're a collaborator, it should pop up quickly). Then submit your pull request.
Now review each other. Open your partner's pull request (you should have gotten an email as a reviewer, and can also find it in the pull requests tab), click Files changed, then Review changes. Leave a comment on a line, choose Approve, and submit.
Then merge only ONE of them. Decide together which pull request goes first and merge it with Merge pull request.
Part 5: The second pull request
Go and look at the one you did not merge, and refresh the page. GitHub now says "This branch has conflicts that must be resolved." You both changed the same lines, and git will refuse to pick a winner.
Whoever submitted the pull request that's still open now needs to fix it. Go back to your machine, and first merge in the other person's edits:
git checkout main
git pull
git checkout <your-name>-crew
git merge main
Note you had to go back to main and pull from there. git pull only updates the branch you are standing on.
Now, git will stop and list the files it could not merge. Open src/main.rs. You will again find markers like this:
<<<<<<< HEAD
const CREW_NAME: &str = "Team Segfault";
=======
const CREW_NAME: &str = "The Borrow Checkers";
>>>>>>> main
Above ======= is your version. Below it is what is already on main. Like before, you need to decide what the file should say in the end, and delete all the markers. There are two of these in src/main.rs and one in README.md.
When you're done, check with cargo run. When it prints both of you under one crew name, you can finish:
git add .
git commit -m "Resolve conflicts: keep both names, one crew"
git push
Refresh the pull request, and you'll see the conflict banner is gone. Now the other person can approve and merge it.
Part 6: Look at what you built
Both of you can try this now:
git checkout main
git pull
git log --graph --oneline
Find the merges and pull requests in the tree.
Talk about it with your partner:
- Both routes put a branch onto
main. What does the pull request give you thatgit mergeon your own machine does not? - Nobody reviewed the Part 2 merge. When would that be fine, and when would it not be?
- Realistically, how could you think about organizing your collaborations to prevent conflicts like the ones that arose today before they happen?
Submitting
Both partners submit, separately, on Gradescope (the assignment called Discussion 2 Activity). You will need to write:
- The URL of the repository you worked in. Both of you submit the same one.
- The output of
git log --graph --onelinefrommain. - One or two sentences: what your conflict was, and how you decided to resolve it.
More git practice
None of these are required, but can provide some additional opportunities to practice (though the best way to practice is just to do it for real!)
Browser, nothing to install
- Learn Git Branching is a visual sandbox for branching, merging, rebasing, and remotes. Start with the Introduction sequence, then Remote. It draws the commit graph as you type which helps you picture what's going on.
- Git Mastery is a level-based game covering staging, branches, stash, reset, and rebase. May feel a little fast at first and its ability to simulate real merging and collaboration is limited.
Desktop apps
- Oh My Git! teaches basic git as a card game, with the commit graph drawn live. Good if the command line is still the part slowing you down (and it gives extra gold stars if you go back and do it at the command line after).
- Git-It walks you through the basics against your real GitHub account. Worth doing for challenges 1 through 7. Stop after "Branches Aren't Just For Birds." Challenges 8 and 10 check your work against a server that has been down recently so that part cannot be completed.
Reading
- Pro Git is the free official book. Chapter 3 is branching, and it has an especially clear explanation of merging.
- GitHub Docs for pull requests, reviews, and everything from Part 3.
- Git Immersion is a guided command-line walkthrough. The examples are in Ruby but the git is the same.
Discussion 3: Rust practice
Tue Sep 22 (B sections) / Wed Sep 23 (A sections)
This discussion included review slides GimKit practice, and code debugging as a group. Those activities are not available online.
Discussion 4: Handcoding and mock code review
Discussion 4 on Sep 29-30 comes the week before the project 1 code review, and a week and a half before the first midterm. To prep for both, we will work through some hand-coding problems and then peer code-review each other's work.
Students should work in pairs, with each person in a pair working on a different problem before swapping for feedback and questions.
The problems are described first, below, and then the code review instructions are available after that for reference.
Problem 1: How much room is left
#![allow(unused)] fn main() { struct Backpack { weights: Vec<u32>, limit: u32, } }
weights holds the weight of each item in the backpack, in grams. limit is the most the backpack can carry.
Write two methods.
(a) room_left gives back how many grams of room are left. If the backpack is already at or over its limit, it gives back 0.
(b) try_add takes the weight of one new item and tries to put it in. If it fits, it goes in and the method gives back true. If it does not fit, the backpack is left alone and the method gives back false.
#![allow(unused)] fn main() { impl Backpack { } }
Worked examples for room_left:
weights | limit | room_left() |
|---|---|---|
[300, 450, 120] | 2000 | 1130 |
[900, 800, 700] | 2000 | 0 |
[] | 2000 | 2000 |
Worked examples for try_add, each call picking up where the last one left off, starting from weights = [300, 450, 120] and limit = 2000:
| call | gives back | room_left() afterwards |
|---|---|---|
try_add(500) | true | 630 |
try_add(700) | false | 630 |
try_add(630) | true | 0 |
try_add(1) | false | 0 |
Problem 2: How many halvings
Write a function halvings that takes a u32 and gives back how many times you can halve it before it reaches 1, using whole-number division. Write both a version with a loop and a version with recursion. Which do you prefer?
Worked examples:
n | halvings(n) | because |
|---|---|---|
| 1 | 0 | already there |
| 8 | 3 | 8, 4, 2, 1 |
| 10 | 3 | 10, 5, 2, 1 |
| 64 | 6 | |
| 1000 | 9 |
Discussion 4 Handcoding Guide
Overview
The actual code review for the project include a rubric that is split across several categories, such as "explain this to me" questions, "what if this were different" questions, Git questions, etc. Due to practical constraints, this mock code review only has 3:
- Explain this to me.
- What if this were different?
- Did you actually write this code?
You will grade each other in an identical manner to how we will grade you for the actual code review, with the following criterion:
| Points | Criterion |
|---|---|
| 3 | Correct, and explains why without prompting. Points at their own code. |
| 2 | Correct after one nudge, or right about what happens but not why. |
| 1 | Partly right. Needs a lot of guidance, or describes the code without explaining it. |
| 0 | Unable to supply any coherent answer. |
There will be two questions for each section, and answering the question correctly should account for the bulk of the grade, the follow-up mostly seperates a two from a three.
Note: This grading criterion only pertains to the first two sections here. The last one will also be graded out of three, but by evaluating how well the student did at climbing the question ladder (see below).
Explain this to me
This section pertains to reasoning through code and explaining your thought process behind writing it.
Problem 1: How much room is left?
Primary Question: What happens when an item fits exactly, such that no space is left over? What does this tell you about using < vs <=?
Secondary Questions:
- Checking the limit in
room_left()with>=vs>doesn't matter here, but why might you want one vs the other, philosophically? - Did try_add call
room_left(), or recompute the total from scratch? Both work, why did you do it the way you did?
Problem 2: How many halvings?
Primary Question: Which do you prefer and why? Do you expect one to be faster than the other, or similar?
Secondary Questions:
- What is your base case in your recursive implementation? What does the recursive call and subsequent stack look like?
- For the iterative case, did you first check if current <= 1? If not, why isn't it necessary to separate it out like in the recursive version?
What if this were different
This section pertains to evaluating hypothetical counterfactuals and explaining how they would have changed your code had they been true.
Problem 1: How much room is left?
Primary Question: How might the composition of our Backpack and its implementation been different if weights were represented as a fixed length array instead of a vector array?
Secondary Questions:
- If we wanted to implement some method
retrievetoBackpackwhich allows us to take out items from the top of the backpack, what abstract data structure shouldweightsbe? - If the first item we put in the bag is the maximum value storable in a
u32representation, what will happen when we add another item?
Problem 2: How many halvings?
Primary Question: Consider the answer you gave to the preference question posited in the first question. What problem might warrant the other option?
Secondary Questions:
- Whole number division in Rust naturally truncates the decimal value, meaning it always rounds down. Would the speed of your algorithm be affected if it instead rounded up?
- Instead of halving the value, assume that we instead quarter the value each time. How do the big O runtimes compare?
Did you actually write this code
This section ensures that you actually wrote your code, and that you can provide actual line-by-line explanations for how it works. In the actual code review, this section is represented slightly differently as a ladder of questions, so this section only contains one question with multiple segments. Allot one point per ladder rung climbed.
Problem 1: How much room is left?
Question Ladder: Point to the line in room_left that ensures you consider every item in the backpack, weight wise. Why did you choose to implement it this way? Are there alternative ways?
Problem 2: How many halvings?
Question Ladder: Point to the line in both of your solutions that ultimately keeps track of how many halvings it takes. What is different about how each is stored? Are each mutable or immutable? Explain.
Answer key
These are what a full-credit answer should touch on. Your partner does not need to use these exact words, but if they miss the core idea of the primary question, that's a 1 at most. The "why" parts are what separate a 2 from a 3.
Explain this to me
Problem 1: How much room is left?
Primary: When an item fits exactly, weight == room_left(), so the check has to be weight <= self.room_left(). For instance, with <, try_add(630) would wrongly return false even though the backpack can hold exactly 630 more grams.
Secondary:
>=vs>inroom_left: whentotal == limit, both branches give back 0 so the output is the same. The reason the check exists is so thatu32can't go negative: iftotal > limit,self.limit - totalwould underflow. Either>=or>protects against that.>=says "full or over means no room" explicitly, while>relies on the subtraction happening to give 0.- Calling
room_left()vs recomputing: calling it avoids duplicating the summing loop, so if the rule for "how much room is left" changes, it only changes in one place. Also reduces boiler plate code. Both are O(n) in the number of items.
Problem 2: How many halvings?
Primary: Either preference is fine if it's justified. Both do the same number of halvings, so both are O(log n) time. The loop uses O(1) extra space, while the recursion uses one stack frame per halving, so O(log n) space. For a u32 that's at most 32 frames, so in practice neither is noticeably faster. The recursive version reads closer to the definition ("one halving, plus however many the half needs").
Secondary:
- The base case is
n <= 1, which gives back 0. Forhalvings(10), the calls stack up ashalvings(10) → halvings(5) → halvings(2) → halvings(1), then unwind:halvings(1)gives 0,halvings(2)gives 1 + 0 = 1,halvings(5)gives 2,halvings(10)gives 3. - No separate check is needed in the loop, because the
while current > 1condition is checked before the first pass. Ifnis 0 or 1, the body never runs andcountstays 0. The loop condition plays the role of the base case.
What if this were different
Problem 1: How much room is left?
Primary: A fixed-length array ([u32; N]) has its size set at compile time, so there's no push. The struct would need an extra field such as count: usize to track how many slots are actually filled. try_add would write to weights[count] and bump count, and it would also have to give back false when the array is full, even if the weight fits. room_left would only sum 0..count, not the whole array. A Vec handles all of this for us by growing as needed.
Secondary:
- Taking items out from the top means the last item in is the first item out, which is a stack (LIFO).
- Nothing bad happens if properly implemented.
try_add(u32::MAX)only succeeds iflimitis alsou32::MAX(au32limit can't be any bigger). After that,room_left()is 0, so any latertry_add(w)withw > 0gives backfalseand the backpack is untouched. The danger is in other ways of writing it:- If
try_addcheckstotal + weight <= self.limit, thenu32::MAX + 1overflows. - If someone builds
Backpack { weights: vec![u32::MAX, 1], limit: 2000 }directly, the summing loop inroom_leftoverflows.
- If
Problem 2: How many halvings?
Primary: Any reasonable pairing works. Recursion fits problems that naturally split into smaller copies of themselves, especially more than one copy where a loop would need to manage its own stack. A loop is the better choice when the recursion would get very deep, e.g. counting down by 1 from a large n makes O(n) stack frames and can overflow the stack, while a loop uses constant space.
Secondary:
- Rounding up (
(current + 1) / 2) is still O(log n). It sometimes takes one extra step, e.g. 10 → 5 → 3 → 2 → 1 is 4 halvings instead of 3. It still stops because for any value of 2 or more, rounding up still makes it smaller. - Quartering takes log₄(n) steps, which is log₂(n) / 2, so about half as many. But logs of different bases differ by only a constant factor, so both are O(log n).
Did you actually write this code
One point per rung, as described above.
Problem 1: How much room is left?
- Point to it: the loop header, e.g.
for i in 0..self.weights.len(), together withtotal += self.weights[i]. - Why: any honest reason tied to their code, e.g. indexing is what they're used to from arrays, or they wanted
iavailable. - Alternatives: Any other valid loop header works, i.e.
for w in &self.weights { total += w; }.
Problem 2: How many halvings?
- Point to it: in the loop version,
count += 1. In the recursive version, the1 +in1 + halvings(n / 2). - How it's stored: the loop keeps a single variable,
count, and updates it in place each pass. The recursive version has no count variable at all. The count is built up out of the values given back as the stack unwinds, with each frame adding 1 to what the frame below it gave back. - Mutable or immutable:
count(andcurrent) must belet mutbecause they change. Everything in the recursive version is immutable, since each call gets its ownnand nothing is ever reassigned.
Discussion 5: A only - Enums and error handling practice
Paste this code into Rust Playground and complete the functions marked with todo!().
The discussion also used slides which are not available here.
#![allow(unused)] fn main() { // All legal values in a simple expression as enum variants #[derive(Debug, PartialEq, Clone, Copy)] enum Token { Num(f64), Plus, Minus, Slash, Star } impl Token { fn parse(self) -> Result<f64, ParseError> { if let Token::Num(x) = self { Ok(x) } else { Err(ParseError::UnexpectedToken(self)) } } } /// All possible errors /// /// *-----------------------* /// - UnexpectedToken: putting two operations together, putting two numbers together, etc. /// - InvalidInput: inputting any non-numerical value thats not an operation /// - TrailingInput: ending an expression without finishing an operation /// - DivisionByZero: dividing by zero /// - EmptyInput: evaluating an expression with nothing in it #[derive(Debug, PartialEq)] enum ParseError { UnexpectedToken(Token), InvalidInput(String), TrailingInput, DivisionByZero, EmptyInput, } // Helper that turns any string into a list, splitting on whitespace fn into_array(input: &str) -> Vec<&str> { input.split_whitespace().collect() } // Helper that reads its input string as a number, rejecting non-finite values like "inf" and "NaN" fn parse_number(input: &str) -> Option<f64> { input.parse::<f64>().ok().filter(|n| n.is_finite()) } /// Create a vector array to hold tokens, then parse the string delimited by spaces to tokenize /// the expression into an executable form fn parse_line(input: &str) -> Result<Vec<Token>, ParseError>{ let mut tokens: Vec<Token> = Vec::new(); let expr: Vec<&str> = into_array(input); todo!() } /// Evaluate the expression. Consider edge cases: what happens when the expression is of length 1? fn eval(input: Vec<Token>) -> Result<f64, ParseError>{ // This consumes our input and turns it into a mutable collection let mut expr = input.into_iter(); // This sets value to expr[0] then pops that value, turns it from Some() -> Result(), unwraps it, then parses it // with Token::parse() before unwrapping it again. We get the number out of the token and raise the relevant // error otherwise. let mut value: f64 = expr.next().ok_or(ParseError::EmptyInput)?.parse()?; todo!() } #[cfg(test)] mod tests { use super::*; // Helper that runs a full line through the tokenizer and the evaluator fn calc(input: &str) -> Result<f64, ParseError> { parse_line(input).and_then(eval) } // ---------- parse_line ---------- #[test] fn parse_line_tokenizes_numbers_and_operations() { assert_eq!( parse_line("1 + 2 - 3 * 4 / 5"), Ok(vec![ Token::Num(1.0), Token::Plus, Token::Num(2.0), Token::Minus, Token::Num(3.0), Token::Star, Token::Num(4.0), Token::Slash, Token::Num(5.0) ]) ); } #[test] fn parse_line_handles_decimals_and_negative_numbers() { assert_eq!( parse_line("-2.5 + 0.25"), Ok(vec![Token::Num(-2.5), Token::Plus, Token::Num(0.25)]) ); } #[test] fn parse_line_ignores_extra_whitespace() { assert_eq!( parse_line(" 1 +\t2 "), Ok(vec![Token::Num(1.0), Token::Plus, Token::Num(2.0)]) ); } #[test] fn parse_line_empty_string_gives_no_tokens() { assert_eq!(parse_line(""), Ok(vec![])); assert_eq!(parse_line(" "), Ok(vec![])); } #[test] fn parse_line_rejects_non_numeric_input() { assert_eq!(parse_line("1 + x"), Err(ParseError::InvalidInput("x".to_string()))); assert_eq!(parse_line("( 1 + 2 )"), Err(ParseError::InvalidInput("(".to_string()))); } #[test] fn parse_line_requires_spaces_between_tokens() { assert_eq!(parse_line("1+2"), Err(ParseError::InvalidInput("1+2".to_string()))); } #[test] fn parse_line_rejects_non_finite_numbers() { assert_eq!(parse_line("inf"), Err(ParseError::InvalidInput("inf".to_string()))); assert_eq!(parse_line("NaN"), Err(ParseError::InvalidInput("NaN".to_string()))); assert_eq!(parse_line("1e999"), Err(ParseError::InvalidInput("1e999".to_string()))); } // ---------- eval ---------- #[test] fn eval_single_number() { assert_eq!(calc("5"), Ok(5.0)); } #[test] fn eval_each_operation() { assert_eq!(calc("1 + 2"), Ok(3.0)); assert_eq!(calc("5 - 8"), Ok(-3.0)); assert_eq!(calc("4 * 2.5"), Ok(10.0)); assert_eq!(calc("9 / 4"), Ok(2.25)); } #[test] fn eval_goes_left_to_right_without_order_of_operations() { // With order of operations these would be 7 and 5 assert_eq!(calc("1 + 2 * 3"), Ok(9.0)); assert_eq!(calc("8 - 2 / 2"), Ok(3.0)); } #[test] fn eval_long_expression() { assert_eq!(calc("10 / 4 - 0.5 * 3 + 1"), Ok(7.0)); } #[test] fn eval_negative_operand() { assert_eq!(calc("3 - -2"), Ok(5.0)); assert_eq!(calc("-3 * -2"), Ok(6.0)); } #[test] fn eval_empty_input() { assert_eq!(calc(""), Err(ParseError::EmptyInput)); assert_eq!(eval(vec![]), Err(ParseError::EmptyInput)); } #[test] fn eval_leading_operation() { assert_eq!(calc("+ 1"), Err(ParseError::UnexpectedToken(Token::Plus))); } #[test] fn eval_two_operations_in_a_row() { assert_eq!(calc("1 + * 2"), Err(ParseError::UnexpectedToken(Token::Star))); } #[test] fn eval_two_numbers_in_a_row() { assert_eq!(calc("1 2"), Err(ParseError::UnexpectedToken(Token::Num(2.0)))); assert_eq!(calc("1 + 2 3"), Err(ParseError::UnexpectedToken(Token::Num(3.0)))); } #[test] fn eval_trailing_operation() { assert_eq!(calc("1 +"), Err(ParseError::TrailingInput)); assert_eq!(calc("1 + 2 *"), Err(ParseError::TrailingInput)); } #[test] fn eval_division_by_zero() { assert_eq!(calc("4 / 0"), Err(ParseError::DivisionByZero)); assert_eq!(calc("4 / 0.0"), Err(ParseError::DivisionByZero)); assert_eq!(calc("4 / -0"), Err(ParseError::DivisionByZero)); } #[test] fn eval_zero_divided_by_number_is_fine() { assert_eq!(calc("0 / 4"), Ok(0.0)); } #[test] fn eval_stops_at_first_error() { // The division by zero comes before the trailing operation assert_eq!(calc("1 / 0 +"), Err(ParseError::DivisionByZero)); } } }
Discussion 8: Review and Practice
One of the activities in discussion today will be practicing drawing full stack-heap diagrams.
Slides
The slides from discussion, as a PDF. If the viewer below doesn't load, use the download link.
Some reminders
- Draw the stack on the left and the heap on the right, at the spot marked
// DRAW HERE(as if the program ran to that point and then paused) - Build the stack from the bottom up, one solid box per function frame, labeled with the function's name. A
{ }block inside a function gets a dashed box on top of its frame. Within a frame, order doesn't matter. - A frame holds every variable its function declares, from the moment it is called. Write
???for any that has no value yet (it should still have a name and type), and(moved)(or x out the pointer/value) for any whose value has moved - Label every variable with its type and any other metadata. A
StringorVechaslenandcapand a slice haslenin addition to pointers. - Draw an arrow from each pointer to the thing it points at. Arrows can go around to the left or the right, whatever's clearer.
Problem 1: types of strings
fn label(word: &str) -> String { let owned = word.to_string(); let count = word.len(); // DRAW HERE println!("{} has {} bytes", owned, count); owned } fn main() { let text = String::from("hello crab"); let piece: &str = &text[6..10]; let lit: &str = "crab"; let out = label(piece); println!("{} | {} | {}", text, out, lit); }
Follow-up questions:
- How many copies of the letters c-r-a-b are in memory when you drew it, and where is each one?
- If
textwere"hello 🦀"instead, what wouldtext.len()be?
Problem 2: on vecs and ints
fn report(score: &i32, history: &Vec<i32>) -> i32 { let best = history[0]; let total = *score + best; // DRAW HERE total } fn main() { let mut score = 40; let bump = &mut score; *bump += 10; let history = vec![70, 65]; let view = &score; let result = report(view, &history); println!("{}", result); }
Follow-up questions:
- How many of
report's arrows end on the heap? - If we didn't use references when passing into
reportand called something likereport(score, history)instead, wouldmainstill compile?
Discussion 10: Traits
A review of traits: what they are, a worked example of defining and implementing one, trait bounds, and the traits you already use (Clone, Copy, PartialEq, Ord). The second half is an exercise, submitted on Gradescope.
Slides
The slides from discussion in PDF. If the viewer below doesn't load, use the download link.
Exercise: Yes, chef!
The exercise is on the Rust Playground, with the instructions in the file. Submit your program and its output on Gradescope.
Discussion 12: Data structures review and practice
Tue Nov 24 (B sections). A sections don't meet this week, so this is the B discussion, plus extra practice for anyone in A or anyone who couldn't make it.
We'll review the material since Midterm 2: traits and generics briefly, then the data structures week in depth.
- Part 1 is review, all of it from lecture
- Part 2 is practice on paper (no coding)
- Part 3 is two hand-coding practice problems
Part 1: Review
Traits and generics
A trait is a promise: any type that implements it has these methods.
trait Describe {
fn describe(&self) -> String; // what the method looks like
}
impl Describe for Player { // how one type keeps the promise
fn describe(&self) -> String {
format!("#{} {}", self.number, self.name)
}
}
#[derive(Debug, Clone, PartialEq)]asks the compiler to write theimplfor you- A generic function works for many types:
fn max<T: PartialOrd>(x: T, y: T) -> T T: PartialOrdis a trait bound: it means any typeT, as long as it can be comparedVec<Box<dyn Agent>>holds values of different types that all keep theAgentpromise. We can't know how big eachAgentis, so theVecholds a pointer to each one, and every element takes up the same space
What each collection requires of its type
The standard library's collections are generic, and each one puts a trait bound on what it stores.
| You write | The type needs | Because |
|---|---|---|
println!("{:?}", x) | Debug | It has to know how to print it |
v.sort() | Ord | Sorting compares pairs with cmp |
BinaryHeap<T> | Ord | It has to know which one is biggest |
HashSet<T>, and the keys of HashMap<K, V> | Eq + Hash | It hashes the key, then compares it to what's in the bucket |
BTreeSet<T>, and the keys of BTreeMap<K, V> | Ord | It keeps the keys in sorted order |
When the compiler says "the trait bound Striker: Ord is not satisfied", it means a method you're using on a Striker requires Striker to have the Ord trait but you haven't implemented it yet. Typically you can fix it by adding the trait mentioned to the derive line.
Derived Ord compares field by field, in the order the fields are declared. (To get a custom order you need to implement a cmp yourself.)
Which structure?
| Need | Use | Under the hood |
|---|---|---|
| Pop the newest | Vec | One block |
| Pop the oldest | VecDeque | One block, a head, % cap |
| Pop the biggest | BinaryHeap | One block, (i - 1) / 2 |
| Is this here? | HashSet | One block of buckets, hash % buckets |
| Look it up by key | HashMap | The same, with a value next to each key |
| Keep it sorted while it changes | A binary search tree, BTreeSet | One block per node, joined by pointers |
The first five are a Vec-shaped block on the heap plus some arithmetic. The binary search tree is the one with a different shape.
What each one costs
| Structure | Operation | Cost |
|---|---|---|
Vec | v[i], push(x), pop() | O(1) |
insert(0, x), remove(0), contains(&x) | O(n) | |
VecDeque | push_back, pop_front, push_front, pop_back | O(1) |
BinaryHeap | peek() | O(1) |
push(x), pop() | O(log n) | |
HashSet, HashMap | contains, get, insert, remove | O(1) average |
| Search tree | search, insert | O(height) |
O(height) is O(log n) when the tree is bushy and O(n) when it has turned into a chain.
Hash tables
A lookup is three steps, however many keys are stored:
- Hash the key to get a number
- Modulo by the number of buckets to get a bucket index
- Compare the key with what's in that bucket
hash("Alice") % 8 = 63350368 % 8 = 0
hash("Bob") % 8 = 66965 % 8 = 5
[0] [1] [2] [3] [4] [5] [6] [7]
Alice Bob
- Collision: the bucket's taken by a different key. Look in the next one, and keep going until you find the key or hit an empty bucket
- Growing: when it's getting close to full the bucket array doubles, and every key is re-hashed, because the modulo step changed (eg
% 8became% 16) - The order you get when you loop over a
HashSetor aHashMapis whatever order the buckets are in. It's effectively random.
Binary heaps
A max-heap is a complete binary tree where every parent is >= its children. Complete means no gaps, so the rows fit end to end in a Vec.
42
/ \
30 20 Vec: [42, 30, 20, 10, 25, 15, 8]
/ \ / \ Index: 0 1 2 3 4 5 6
10 25 15 8
- Parent of index
i:(i - 1) / 2. Children ofi:2 * i + 1and2 * i + 2 - Push: put the new value at the end, then bubble up. Swap with the parent while it's bigger than its parent
- Pop: take the root, move the last value into the root's spot, then bubble down. Swap with the larger child while a child is bigger
- One swap per row, about log n rows, so both are O(log n)
- Only parent and child are ordered. Siblings can be in any order, and the
Vecusually isn't sorted
VecDeque
One block, used as a ring. head is the slot holding the front, and len counts the elements.
slot: 0 1 2 3
┌─────┬─────┬─────┬─────┐
│ 50 │ 20 │ 30 │ 40 │ head: 1 len: 4
└─────┴─────┴─────┴─────┘
▲
head prints [20, 30, 40, 50]
- Element
iof the queue is at slot(head + i) % cap push_back: write at slot(head + len) % cap, thenlen + 1pop_front: take what's athead, thenheadmoves forward one slot andlen - 1push_front:headmoves back one slot and the value goes there. Back from slot 0 wraps to the last slotpop_back: take the last element,len - 1.headstays put- Nothing ever shifts, so all four are O(1). When the ring is full, it doubles the way a
Vecdoes (and unwraps/resets the ring)
Lists and trees
A node that holds another node needs a pointer, and the pointer is optional so the structure can end, which means we need both Option and Box:
struct Node { // a linked list
value: i32,
next: Option<Box<Node>>,
}
struct Node { // a binary tree
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
- Every
Box::newis its own block on the heap - A recursive type gets a recursive function:
Noneis the base case,Somerecurses
fn len(list: &Option<Box<Node>>) -> usize {
match list {
None => 0, // the end: nothing here
Some(node) => 1 + len(&node.next), // this one, plus the rest
}
}
Search trees
The BST property, at every node: everything in the left subtree is smaller, everything in the right subtree is bigger.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
- Search: compare with the node. Smaller, go left. Bigger, go right. Stop when you find it or fall off the bottom
- Insert: search for the value. The spot where the search falls off is where the new leaf goes
- In order: left subtree, then the node, then the right subtree gives the values sorted
- One comparison per row, so search and insert are O(height)
- Insert values in sorted order and every one goes right. The tree is a chain, and O(height) is O(n)
Two kinds of tree
BinaryHeap | Search tree | |
|---|---|---|
| The rule | Parent >= both children | Left < node < right, for whole subtrees |
| Shape | Complete, no gaps | Any (binary) shape |
| Memory | One block | One block per node |
| Find a child | Arithmetic, 2i + 1 | Follow a pointer |
| Biggest | peek, O(1) | Keep going right, O(height) |
Is x in here? | O(n), look at everything | O(height) |
| Insert | O(log n), bubble up | O(height), fill the hole |
| Everything in order | Sort it, O(n log n) | Left, node, right: O(n) |
Part 2: Practice on paper
No code to write in this part. Draw, trace, and explain.
Problem 1: what's the compiler asking for?
struct Song { title: String, plays: u32 }
For each line, name the trait or traits Song needs before it compiles, if any.
println!("{:?}", song);if song_a == song_b { ... }playlist.sort();whereplaylistis aVec<Song>seen.insert(song);whereseenis aHashSet<Song>heap.push(song);whereheapis aBinaryHeap<Song>queue.push_back(song);wherequeueis aVecDeque<Song>
Follow-up. We derive everything BinaryHeap<Song> needs, push "Yesterday" (20 plays), "Dreams" (27), and "Imagine" (24), then pop once. Which song comes out, and why?
Problem 2: build a hash table
The keys are jersey numbers. The hash function is trivial: hash(n) = n. The table has 8 buckets, so the bucket index is n % 8. On a collision, look in the next bucket, and past bucket 7 comes bucket 0.
Insert these, in this order: 23, 10, 15, 4, 31, 42
[0] [1] [2] [3] [4] [5] [6] [7]
- Fill in the table.
contains(&31): which buckets does it look in, in order?contains(&39): which buckets does it look in, and how does it know to stop?- Three of the six keys wanted the same bucket. Which property of a good hash function is this one missing?
- The table doubles to 16 buckets. Re-place the six keys in the same order. How many of them end up in a different bucket, compared with before?
Problem 3: hashing, short answers
- You print a
HashSetof team names, run the program again, and the names come out in a different order. Why? What would you do to print them alphabetically? winsis aHashMap<String, u32>with no entry for "The Ducks". What doeswins.get("The Ducks")give you? What doeswins["The Ducks"]do?- A loop calls
roster.contains(&name)once for each of 2,000 names, androsteris aVecof 50,000 names. Roughly how many comparisons is that in the worst case? How many lookups ifrosteris aHashSet?
Problem 4: read the Vec
Each of these is the Vec inside something that claims to be a max-heap. Draw each one as a tree and say whether it's a valid max-heap. If it isn't, name the parent and child that break the rule.
a. [88, 70, 65, 40, 52, 30, 61]
b. [50, 45, 48, 20, 46, 10, 47]
c. [10, 9, 8, 7, 6, 5, 4]
- Valid or not, for each?
- Is a
Vecsorted from biggest to smallest always a valid max-heap? Is a valid max-heap always sorted? - In a max-heap of n values, where can the smallest value be? What's the complexity of finding it?
Problem 5: push, then pop
Start from heap a in Problem 4:
- Push 75. Draw the tree and write the
Vecafter the swaps. How many swaps? - Now pop. What comes out? Draw the tree and write the
Vecafter the swaps. - In step 2, the value that moved to the root had two children bigger than it. Which one did you swap with, and what would happen if you went the other way?
Problem 6: trace a ring
A VecDeque<i32> called line with capacity 5, starting empty with head at slot 0:
push_back(3), push_back(8), push_back(5)
push_front(1)
pop_back()
push_front(6)
push_back(9)
- Draw the block after every line, with
headandlennext to it. - What does
println!("{:?}", line)print at the end? - Which slot holds the front? Which slot holds the back?
line[2]is which slot, and which value?- The ring is now full. What happens on the next
push_back(4)?
Problem 7: grow a search tree
Start from an empty binary search tree and insert these, in this order: 20, 9, 31, 4, 15, 26, 42, 12
- Draw the tree.
contains(&tree, 15): which nodes does it visit, and what comes back?contains(&tree, 28): which nodes does it visit, and what comes back?- Insert 28. Where does it go?
- Read the tree in order: left subtree, node, right subtree. What do you get?
- How many blocks are on the heap now? What would be on the stack?
- Say the same nine values went in smallest to biggest. What's the height of that tree, and what does a search cost?
Problem 8: which structure?
For each one, pick Vec, VecDeque, BinaryHeap, HashSet, HashMap, or a search tree (BTreeSet or BTreeMap). Say why in a few words, and name the trait the stored type or key needs, if any.
- A music app's "up next" list: songs play in the order you added them, and "play next" cuts one in at the front.
- Matchmaking for an online game: players join the waiting room all the time, and the highest-rated one waiting always gets matched first.
- From a season's list of goal events, find how many goals each player scored. (This one's trickier - think about how you'd do it by hand first.)
- The discard pile in a card game (you can only ever take the top card).
- Online Scrabble checks each word you play against a dictionary of 200,000 words.
- A leaderboard of players by rating that changes all day, and has to answer "everyone rated between 1500 and 1600" quickly.
Problem 9: costs, from memory
Cover the cost table in Part 1 and fill this in. n is the number of elements stored.
| Operation | Cost | Why, in a few words |
|---|---|---|
Vec: remove(0) | ||
Vec: contains(&x) | ||
VecDeque: pop_front() | ||
BinaryHeap: peek() | ||
BinaryHeap: push(x) | ||
HashSet: contains(&x) | ||
| Search tree, bushy: search | ||
| Search tree, built from sorted input: search | ||
BinaryHeap: "is x in here?" |
Part 3: Hand-coding
Focus on the overall shape rather than the & or * details.
Problem 10: the first repeat
A league needs every jersey number to be unique. Write first_repeat, which walks a slice of jersey numbers and returns the first number that shows up for a second time, or None if every number is different.
use std::collections::HashSet;
fn first_repeat(numbers: &[u32]) -> Option<u32> {
// your code here
}
fn main() {
println!("{:?}", first_repeat(&[23, 10, 7, 10, 23])); // Some(10)
println!("{:?}", first_repeat(&[23, 10, 7])); // None
}
The methods you need:
| Method | What it does |
|---|---|
HashSet::new() | An empty set |
set.insert(x) | Adds x to the set |
set.contains(&x) | true if x is in the set |
Follow-up.
- What's the Big-O of your function, for n numbers?
- What would the Big-O be if
seenwere aVecand you calledseen.contains(&x)?
Problem 11: how tall is the tree?
Here's the tree node from lecture, and len for a linked list. Write height for the tree: the number of rows. An empty tree has height 0, and a tree with one node has height 1.
struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
// For reference: the length of a linked list, whose node has one `next`
fn len(list: &Option<Box<ListNode>>) -> usize {
match list {
None => 0,
Some(node) => 1 + len(&node.next),
}
}
fn height(tree: &Option<Box<Node>>) -> usize {
// your code here
}
Follow-up.
- What does
heightreturn for the tree you drew in Problem 7, after inserting 28? - What's the Big-O of
height, for n nodes? Can it skip a subtree the waycontainsdoes?
In-Class Activities
Most lectures end with a hands-on activity, taking the last third of class.
Activity numbers match lecture numbers: Activity 3 belongs to Lecture 3.
The rest appear here as they are released, alongside any materials that go with them.
Activity 1: Syllabus Review
Sheet 1: keep this one
By Friday
- Fill out the intro survey linked in your welcome 2a. Install Git Bash (if on Windows)
- Complete the pre-lecture task for Friday on Gradescope
- Bring your laptop Friday!
Where things live
| Course site | rust4ds.github.io/ds210-fa26-lectures |
| Piazza | Announcements and questions |
| GitHub | Receive and work on your assignments |
| Gradescope | Submit work, get feedback, see standings |
| Echo360 | Lecture recordings |
The shape of your grade
50% exams, 20% active engagement, 15% code reviews, 15% autograded work.
You must attend your assigned lecture and discussion to get participation credit.
Finding me
Office hours. Drop-in, no sign-up, CDS 1506. Mondays and Wednesdays 9:30 - 10:30am.
Coffee chats. 20-minute appointments, Fridays 9:30 - 10:30am and every other Tuesday 2:00 - 3:00pm starting September 8. Sign up at calendly.com/laurenbw-bu/coffee-chats. One rule: we do not talk about the course.
Your teaching staff
Course assistants: Kesar Narayan, Lingjie Su Section A TAs: Matt Morris, Gabriel Burr Section B TAs: Emir Tali, Kristen Bestavros, Nia Naresh Kumar
What to bring to every lecture
- Something to write with (we'll provide handouts for notes)
- Your laptop, closed unless we are actively coding
Notes and Announcements
Sheet 2: hand this one in
One sheet per group, with everyone's names on it.
Group members:
Concrete questions:
-
How is project work submitted?
-
What happens if you submit work a day late?
-
What is one way to use AI that is acceptable, and one way that is in violation of course policies?
-
What would it take to get full credit for attendance and participation?
-
If you have accommodations for exams, when should you book with the testing center?
-
How could you get a zero on a project, even if all of your tests pass?
Open-ended questions:
-
What parts of the course policies seem standard and what parts seem unique?
Standard Unique
-
Identify 2-3 things in the syllabus that concern you
-
What strategies could you use to address these concerns?
-
Identify 2-3 things on the syllabus that you're glad to see
-
List three questions you have about the course that aren't answered in the syllabus
Solutions
The concrete questions have answers in the syllabus. The open-ended ones do not.
- Submitting project work. Each checkpoint and project is a Gradescope assignment that links to a base repository on GitHub. You make your own copy, commit your work there as you go, and paste the URL of your repo into Gradescope. We download it and run the tests.
- A day late. Up to 48 hours late still qualifies for up to 80% credit. After 48 hours, late work is not accepted without prior arrangements for extraordinary circumstances. Late projects are still code-reviewed on the normal schedule.
- AI use. Acceptable: using it to understand a concept, debug your own code, or brainstorm, and citing what you used and how in your project README. A violation: leaning on it so heavily that you cannot explain the code you submitted, which earns a zero on the whole assignment even if the tests pass. Not citing your use is also a violation.
- Full credit for attendance and participation. Be in your assigned lecture and discussion sections, and get recorded present: activity sheets, in-class Gradescope tasks, and cold calls. Each of the three attendance periods has 18 points of sessions, and 16 earn the full 5%, so you can miss two lectures or one discussion per period, no questions asked.
- Testing center. Within the first two weeks of the semester, for all three exam dates: October 9, November 6, and December 14.
- A zero with passing tests. Two ways: skip your code review, or overuse GenAI to the point that you cannot explain your code at the review. Both zero out the entire project, including the autograded portion.
Activity 2: Build a Treasure Hunt
Solo/group: Solo submissions but feel free to work together
Submission: On gradescope ("Lecture 2 Activity")
In Class Activity Part 1: Access/Install Terminal Shell
Directions for MacOS Users and Windows Users.
macOS Users:
Your Mac already has a terminal! Here's how to access it:
-
Open Terminal:
- Press
Cmd + Spaceto open Spotlight - Type "Terminal" and press Enter
- Or: Applications -> Utilities -> Terminal
- Press
-
Check Your Shell:
echo $SHELL # Modern Macs use zsh, older ones use bash -
You are ready. Nothing to install today. Go to Part 2.
Windows Users:
Windows has several terminal options. For this class we strongly recommend/require Git Bash, unless you already are very comfortable using another shell on your machine. (PowerShell aliases some commands to be Linux-like, but they are fairly quirky.)
- Download Git for Windows from git-scm.com
- During installation, take the default options
- Open "Git Bash" from Start menu
Verify Your Setup (Both Platforms)
pwd # Should show your current directory
ls # Should list files
which ls # Should show the path to the ls command
echo "Hello" # Should print Hello
Part 2: Build a Treasure Hunt
You are going to build a small game out of nothing, using only the keyboard. No clicking, no dragging, and no Finder/File Explorer.
At the end you will get to step back and see what you built and... not see what you built?
What you need today - quick reference
pwd # where am I?
ls # what is here?
ls -a # what is here, including hidden things
cd foldername # go into a folder
cd .. # go up one level
mkdir foldername # make a folder
echo "text" > file.txt # write text into a file, replacing whatever was there
echo "text" >> file.txt # add text to the end of a file
cat file.txt # show me the file
nano file.txt # edit a file (ctrl-O saves, ctrl-X quits)
Tab completes a path you have started typing. Up arrow brings back your last command. Use both constantly.
There is a much longer cheat sheet at the bottom but you won't need it for this activity.
Your steps
0. Decide where your course work lives, and make it from the terminal.
You will want one folder to hold everything for this course. Pick now and stick with it. Here's how to do it from the command line.
cd ~ # start at home
mkdir ds210 # make the folder
cd ds210 # go into it
pwd # write this down. This is home base
I (Prof. Wheelock) keep all my code projects in ~/projects, so mine folder is ~/projects/ds210. If you would rather have yours on the Desktop, you can cd ~/Desktop before the mkdir.
Do not make this one by clicking. It's faster now, but once you get good at the command line, you'll work faster than you ever could with point-and-click-ing.
1. Make the hunt, and step inside.
mkdir treasure_hunt
cd treasure_hunt
pwd
That last line should end in /treasure_hunt. If it does not, you are not where you think you are. Sort that out before going on, because everything after this happens here.
2. Sign the guest book.
Make a file called guest_book.txt with your name in it.
echo "Ada Lovelace" > guest_book.txt
cat guest_book.txt
Remember, > means "send this output into that file", creating it if it does not exist. cat shows you it worked.
3. Ask your computer some questions, and keep the answers.
Run each of these. >> adds to the end of the file. > would throw your names away, so the difference matters here.
whoami >> guest_book.txt # your username
hostname >> guest_book.txt # your computer's name
pwd >> guest_book.txt # where you are standing
echo $HOME >> guest_book.txt # your home directory
Now cat the file again. You should see five lines (and wow, you never opened an editor!)
4. Leave a clue.
Make a new file called clue_1.txt containing: The treasure is hidden in plain sight (you have all the tools you need now to figure out how).
5. Build the secret chamber.
mkdir secret_chamber
cd secret_chamber
Inside it, make clue_2.txt containing: Look for a hidden file
6. Hide the treasure. Then watch it vanish.
Make a file called .treasure_map.txt containing: Congratulations. You found the treasure
Note the dot at the front of the name. Now run these two, in this order, and look carefully:
ls # what do you see?
ls -a # now what do you see?
Answer this in writing, appending to the guest book one level up:
echo "A file whose name starts with a dot is ..." >> ../guest_book.txt
.. means the directory above this one, so you are writing into a file you are not standing in.
A hidden file isn't that deep - it's not protected, encrypted, or special. Its name starts with a dot, and ls skips those unless you ask with -a. This is why your folders looks so tidy in Finder or File Explorer and so crowded in the terminal.
7. Stand back and look at what you built.
cd ..
ls -R
That will show you every folder and file you made, all at once. You did all of that without your mouse!
8. Make a zip of it. Change to (cd to) the parent directory of treasure_hunt first. Then, the command is different on each platform:
- Mac:
zip -r treasure_hunt.zip treasure_hunt - Windows, in Git Bash:
tar.exe -a -c -f treasure_hunt.zip treasure_hunt
9. Upload treasure_hunt.zip to Gradescope. Next time we introduce git and GitHub, and we will use that from then on.
10. Optional, for bragging rights. Write a shell script that does all of the above in one go, and upload that too!
Reference: much more than you needed today
Finding the path of something you can already see
Sometimes you will have a folder in Finder or File Explorer and need its path in the terminal. You have a couple options:
1. Drag it into the terminal.
Just drag the folder or file icon into your terminal window annd it will type the path for you. A common use is to first type cd (with a space), then drag a folder from your file browser and hit enter to cd into a folder when you don't know its path.
- Works in Terminal and iTerm2 on a Mac, and in Git Bash on Windows
- Git Bash converts the Windows path into one bash understands, so you get
/c/Users/you/Desktop/ds210and notC:\Users\you\Desktop\ds210 - It is a feature of the terminal window, not the shell, so it may not work in VS Code's built-in terminal or other termminals
2. Ask the file browser.
- Mac: right-click (ctrl-click) the folder/file, hold
Option, and "Copy as Pathname" appears. OrCmd+Ifor Get Info and read "Where" (you can highlight the path there and right click to "Copy as Pathname" as well) - Windows: shift-right-click and "Copy as path". You will get backslashes, so swap them for forward slashes and put
/c/at the front in place ofC:\
Platform-Specific Tips
Mac, Linux, and Windows in Git Bash:
- Your home directory is
~or$HOME. This is the same in Git Bash as it is on a Mac - Hidden files start with a dot (.)
- Try
which commandto find where a command is located - Use
man commandfor detailed help. Git Bash has noman, so usecommand --helpthere instead
Windows outside Git Bash (Command Prompt or PowerShell):
- Your home directory is
%USERPROFILE%(Command Prompt) or$env:USERPROFILE(PowerShell) - Hidden files have the hidden attribute (use
dir /ahto see them) - Use
Get-Help commandin PowerShell orhelp commandin Command Prompt for detailed help - Try
where commandto find where a command is located - A warning: the course notes, the activities, and your TAs all assume Git Bash. We can help you only so far out here. If you are not already comfortable in PowerShell, switching to Git Bash now will save you trouble all semester
Universal Tips:
- Use Tab completion to avoid typing long paths
- Most shells support command history (up arrow or Ctrl+R)
- Combine commands with pipes (
|) to chain operations - Search online for "[command name] [your OS]" for specific examples
Basic Navigation & Listing
# Navigate directories
cd ~ # Go to home directory
cd /path/to/directory # Go to specific directory
pwd # Show current directory
# List files and directories
ls # List files
ls -la # List all files (including hidden) with details
ls -lh # List with human-readable file sizes
ls -t # List sorted by modification time
Finding Files
# Find files by name
find /home -name "*.pdf" # Find all PDF files in /home
find . -type f -name "*.log" # Find log files in current directory
find /usr -type l # Find symbolic links
# Find files by other criteria
find . -type f -size +1M # Find files larger than 1MB
find . -mtime -7 # Find files modified in last 7 days
find . -maxdepth 3 -type d # Find directories up to 3 levels deep
Counting & Statistics
# Count files
find . -name "*.pdf" | wc -l # Count PDF files
ls -1 | wc -l # Count items in current directory
# File and directory sizes
du -sh ~/Documents # Total size of Documents directory
du -h --max-depth=1 /usr | sort -rh # Size of subdirectories, largest first
ls -lah # List files with sizes
Text Processing & Search
# Search within files
grep -r "error" /var/log # Search for "error" recursively
grep -c "hello" file.txt # Count occurrences of "hello"
grep -n "pattern" file.txt # Show line numbers with matches
# Count lines, words, characters
wc -l file.txt # Count lines
wc -w file.txt # Count words
cat file.txt | grep "the" | wc -l # Count lines containing "the"
System Information
# System stats
df -h # Disk space usage
free -h # Memory usage (Linux)
system_profiler SPHardwareDataType # Hardware info (Mac)
uptime # System uptime
who # Currently logged in users
# Process information
ps aux # List all processes
ps aux | grep chrome # Find processes containing "chrome"
ps aux | wc -l # Count total processes
File Permissions & Properties
# File permissions and details
ls -l filename # Detailed file information
stat filename # Comprehensive file statistics
file filename # Determine file type
# Find files by permissions
find . -type f -readable # Find readable files
find . -type f ! -executable # Find non-executable files
Network & Hardware
# Network information
ip addr show # Show network interfaces (Linux)
ifconfig # Network interfaces (Mac/older Linux)
networksetup -listallhardwareports # Network interfaces (Mac)
cat /proc/cpuinfo # CPU information (Linux)
system_profiler SPHardwareDataType # Hardware info (Mac)
Solutions
Steps 4, 5, and 6 use the same move as step 2: echo with > makes a file with one line in it.
echo "The treasure is hidden in plain sight" > clue_1.txt # step 4
mkdir secret_chamber # step 5
cd secret_chamber
echo "Look for a hidden file" > clue_2.txt
echo "Congratulations. You found the treasure" > .treasure_map.txt # step 6
In step 6, ls shows only clue_2.txt. ls -a adds .treasure_map.txt, plus . and .., which are the directory itself and its parent. A file whose name starts with a dot is hidden from a plain ls, and from Finder and File Explorer, and nothing more than that.
Step 7's ls -R from inside treasure_hunt prints what is here, then each subdirectory followed by what is in it:
clue_1.txt guest_book.txt secret_chamber
./secret_chamber:
clue_2.txt
-R skips the dotfile too. ls -Ra shows everything.
Step 10, the script. Every line is a command you already ran, in order. Save it as build_hunt.sh in your ds210 folder and run it from there with bash build_hunt.sh (though you'll need to make sure treasure_hunt doesn't already exist as a directory for it to work!).
#!/bin/bash
mkdir treasure_hunt
cd treasure_hunt
echo "Ada Lovelace" > guest_book.txt
whoami >> guest_book.txt
hostname >> guest_book.txt
pwd >> guest_book.txt
echo $HOME >> guest_book.txt
echo "The treasure is hidden in plain sight" > clue_1.txt
mkdir secret_chamber
cd secret_chamber
echo "Look for a hidden file" > clue_2.txt
echo "Congratulations. You found the treasure" > .treasure_map.txt
echo "A file whose name starts with a dot is hidden from a plain ls" >> ../guest_book.txt
cd ..
ls -R
Activity 3: Put the Program Together
The scenario
You are writing a small program to help you keep track of your quiz scores. It should:
- Start with the scores you already have
- Add a new score you just got back
- Work out the average
- Print a different message depending on how you are doing
You have all the pieces below, but they are in the wrong order. Some of them are commands you type in the shell, and some of them are lines of Rust that go inside your program file.
Directions
- Get in groups of 2-3
- Send one person up to get a packet
- Write everyone's names on the submission sheet
Do a quick check of your strips: you should have 24, all different. If you are missing any, check out the list on the screen and make any you're missing out of scrap.
Sort the strips into two columns on the page:
- Your shell: Things you type at the terminal, in the order you'd type them
- Your file,
src/main.rs: Lines of Rust, in the order they belong in the file
Things to think about as you go:
- Order matters in both columns. Think about what has to exist before each step can work
- Not every strip is essential. If you think something is optional, put it where you would actually use it and be ready to say why
- You won't know what all the Rust stuff means yet, but do you know enough to make an educated guess?
We'll take the last few minutes to share solutions.
The strips
Cut along the dashed lines. One set per group.
println!("Good work! Average: {:.1}", average);cargo runscores.push(88);let average = total as f64 / scores.len() as f64;cargo new grade_calculator} else if average >= 80.0 {nano src/main.rslet total: i32 = scores.iter().sum();if average >= 90.0 {touch README.md./target/debug/grade_calculatorfn main() {cargo buildprintln!("Keep trying! Average: {:.1}", average);let mut scores = vec![85, 92, 78, 96];ls -lacd grade_calculatorecho "This is a grade average calculator" > README.md} else {}}println!("Excellent! Average: {:.1}", average);println!("You have {} scores so far.", scores.len());cat src/main.rs
Sorting sheet
Names: _______________________________________________________________
Sort the strips into the two areas below. Order matters in both, for different reasons. Not every strip is essential; if you think one is optional, put it where you would actually use it and be ready to say why.
src/main.rs
Solutions
Shell column:
cargo new grade_calculator
cd grade_calculator
ls -la
touch README.md
echo "This is a grade average calculator" > README.md
nano src/main.rs
cat src/main.rs
cargo run
Or, for the last step, the two-step version:
cargo build
./target/debug/grade_calculator
src/main.rs column:
fn main() { let mut scores = vec![85, 92, 78, 96]; scores.push(88); println!("You have {} scores so far.", scores.len()); let total: i32 = scores.iter().sum(); let average = total as f64 / scores.len() as f64; if average >= 90.0 { println!("Excellent! Average: {:.1}", average); } else if average >= 80.0 { println!("Good work! Average: {:.1}", average); } else { println!("Keep trying! Average: {:.1}", average); } }
Which strips are optional
Several of the shell strips could be dropped without breaking the program:
ls -laandcat src/main.rsonly look at things - they're good things to do but not essential, and could go a few placestouch README.mdis redundant, becauseecho "..." > README.mdon the next line creates the file anyway. So does>>, which appends but still creates the file if it isn't there.echo "..." > README.md(and so the README entirely) is technically not needed to run the program. It is good practice, though!cargo buildplus./target/debug/grade_calculatoris the alternative tocargo run, not an addition to it. Either path is right, but you don't need both.
Nothing in the Rust column was designed to be optional.
Activity 4: Set Up Your Project Repo
Project 1 has been released as of today. This activity helps you get started.
Work side by side and help each other, but everyone will make their own copy of the repo and submit separately on gradescope.
Part 1: Make your own copy
- Make sure you have a GitHub account.
- Go to the project repo on GitHub: https://github.com/rust4ds/ds210-fa26-project-1. The full project instructions are on the course website, which links there too.
- Click the green Use this template button, then Create a new repository.
- Name it
ds210-fa26-project-1, the same as ours, so it is easy for us to find when you ask for help. Set it to Private. Then click Create repository.
Your copy is yours. Nobody else can see it, including the rest of the class.
Wait, isn't this what forking is for?
Almost, though the difference is worth understanding, because you will eventually encounter forking too.
Use this template makes an independent copy. Your repo starts with our files and then has nothing more to do with ours. That is what we want here: you are starting your own project, and your work should be yours and private.
Fork also makes a copy, but GitHub remembers where it came from. Your fork is listed publicly on the original repo, you get a button to pull in the original's later changes, and you can open a pull request to offer your changes back. The main reason we're not using forks here is it would force everyone's work to be visible to everyone else.
The Fork button sits in the upper right, and you will use it eventually, just not today:
Part 2: Clone
- Still in GitHub, navigate to your own copy of the repo. Above the list of files, click the green "Code" button, select GitHub CLI (assuming you've set up the CLI) and copy the code snippet (if you don't have the CLI, copy the HTTPS link).
- In your terminal, paste the copied code snippet, or type
git cloneand then the HTTPS link if not using the CLI, hit enter to complete the cloning process.
Part 3: Make a change
-
Open
README.mdand put your name on the author line, replacing_your name here_. Two ways, pick whichever you like:- Stay in the terminal.
cdinto your cloned repo, and thennano README.mdopens it right there. Edit the line, then Ctrl+O and Enter to save, Ctrl+X to quit. Those are Control on Mac too, not Command - Use your editor.
code .opens the whole project in VS Code. If that command is not found, you skipped thecodestep in the setup session, so use File, then Open Folder instead
- Stay in the terminal.
-
Before you commit, ask git what you did:
git status # README.md is modified git diff # one - line and one + line reflects one line edit
Part 4: Commit and push
- Save (commit) and move (push) your change to GitHub (
git add,git commit -m "...",git push) - Check GitHub in your browser and confirm your name is on the README
- Submit the URL of your repo to the Gradescope assignment L4 Activity. Two ways to get it if you have lost the browser tab: run
git remote -v, which prints it, or look at the first linegit pushprinted a moment ago, which starts withTo https://github.com/....
Troubleshooting
Most issues should have been prevented by carefully completing the full git/GitHub set up process in Discussion 1 - review Dicsussion 1 first, and you've completed those steps, ask for help.
If you weren't able to complete these steps by the end of class, instead of your repo URL (if you don't have one) please type a short description of how far you got and where you are blocked.
Activity 5: Compiler Error Hunt
What you are doing
Working in pairs, in the Rust Playground: https://play.rust-lang.org
Break the program below as many different ways as you can, and read what the compiler says each time.
Goal: at least 8 different compiler errors. There is room for 12 on your sheet if you get on a roll.
Why we use the Playground
VS Code underlines your mistake before you ever compile. That is useful most of the time, but not today, because today's exercise is all about hitting the errors and reading them!
It's also a lot faster to get going.
The program
Paste this in and Run it first, so you know it works before you touch it.
fn main() { let temps_c = vec![14.0, 17.5, 21.0, 19.5, 23.0]; let mut warm_days = 0; for i in 0..temps_c.len() { let c = temps_c[i]; let f = c * 9.0 / 5.0 + 32.0; println!("Day {}: {:.1}C is {:.1}F", i + 1, c, f); if c > 18.0 { warm_days += 1; } } let total: f64 = temps_c.iter().sum(); let mean = total / temps_c.len() as f64; println!("Mean high: {:.1}C", mean); println!("Warm days: {} of {}", warm_days, temps_c.len()); }
It should print five days, a mean of 19.0C, and 3 warm days.
The activity loop
- Make one change that breaks the code
- Run it
- Read the error over
- Write it on your half sheet: what you changed, and what the error is (in brief)
- Undo your change, and break it a different way
Make just one change at a time so you can tell what error message belongs to what.
Some ideas
- Change something's type
- Take a keyword away
- Mess with punctuation and variable names
- Ask for something that does not exist
- Give
println!the wrong number of things to print
Warnings are not errors. If you run Clippy from the Tools menu it will suggest ways to rewrite code that already works. Interesting, but it does not count for the hunt.
Solutions: the compiler errors we found
- Drop
mutfromwarm_days: E0384, cannot assign twice to immutable variable - Type
totalasi32: E0277, a value of typei32cannot be made by summing over&{float} - Drop
as f64: E0277, cannot dividef64byusize - Delete a semicolon: expected
;, foundprintln - Misspell
temps_cin the loop: E0425, cannot find value in this scope - Write
if c > 18: E0277, can't compare{float}with{integer} - Remove one argument from
println!: 3 positional arguments in format string, but there are 2 - Write
warm_days += 1.0: E0277, cannot add-assign{float}to{integer} - Put
"17.5"in the vec: E0308, mismatched types - Rename
main: E0601,mainfunction not found - Delete a closing brace: this file contains an unclosed delimiter
- Index
temps_c[i + 1]: compiles, then panics at runtime with index out of bounds - Delete a
!: E0423: expected function, found macro - Try to index like
0[0]: E0608 cannot index into a value of type{integer} - Add
.len()tomean: E0599, no method namedlenfound for typef64in the current scope
Warnings and non-errors too:
- Add
mut: warns you don't need it - Delete
lnfromprintln!: it still works (but prints funny) - Delete
Vec!: nothing seems to change (but the type oftemps_cchanges)
Activity 6: Variables, Mutability, and Types Exploration
Part 1: Hypothesis Time
You can work solo or in groups, but EACH person write down your predictions for each "What If" question below. Don't look anything up - just discuss and make your best guesses!
Binary and Number Representation
- What is 63 in binary (hint: it's 64-1)?
- What decimal number is
1100in binary (if it's positive)? - In 4-bit two's complement, what would -4 look like?
Type Compatibility - Will These Compile?
For each code snippet, predict: will it compile? (Why or why not?)
-
#![allow(unused)] fn main() { let x: i32 = 42; let y: i16 = 100; let sum = x + y; } -
#![allow(unused)] fn main() { let price = 19.99; let tax_rate: f32 = 0.08; let total = price + (price * tax_rate); } -
#![allow(unused)] fn main() { let age: u8 = 25; let negative_age = -age; }
Shadowing
-
Are these equivalent? If yes, why, if not, what is different at the end?
let mut x = 5; x = 6;let x = 5; let x = 6;
-
Can you shadow with a different type? What will happen with:
#![allow(unused)] fn main() { let x = 5; let x = "hello"; } -
What will this print?
#![allow(unused)] fn main() { let x = 10; { let x = x + 5; println!("Inner: {}", x); } println!("Outer: {}", x); }
Overflow Behavior
- What happens when you overflow? Since
u8max is 255, what will this do?
#![allow(unused)] fn main() { let x:u8 = 250; println!("Outer: {}", x+10); }
Part 2: Test Your Hypotheses
Now visit Rust Playground and test your predictions! For each question, write code to test your hypothesis and record on your paper what you discovered:
- Was your hypothesis correct?
- What did you discover?
- Did anything surprise you?
Testing Strategy:
- Questions 1-3: Skip checking, we'll go over it together
- Questions 4-6: Copy the code snippets and see if they compile
- Questions 7-10: Write small test programs to verify your predictions
Solutions
111111. Six ones, because 64 is 2^6 and 63 is one less121100. The same bits as question 2, which is the point: you need to know what type something is to know how to interpret the bits- No. E0308 mismatched types, then E0277, cannot add
i16toi32. Needsx + y as i32 - Yes, and
totalis21.5892.pricehas no written type, and multiplying by anf32makes it one - No. E0600, cannot apply unary
-tou8, "unsigned values cannot be negated". Switching toi8compiles - Both compile and both end at 6.
mutreuses one variable, shadowing makes a second that hides the first - Yes, prints
hello. Shadowing can change the type,mutcannot Inner: 15thenOuter: 10. The innerletis a newxthat dies with the block.- It depends on whether Rust can see it coming. Written exactly like this, with both numbers known at compile time, it does not compile at all: "this arithmetic operation will overflow, attempt to compute
250_u8 + 10_u8". If the 250 came from somewhere the compiler cannot see, like user input, a debug build panics at runtime with "attempt to add with overflow", and a release build wraps around silently and prints4 - No, it does not even compile:
deny(arithmetic_overflow)catches it because the compiler can do the sum itself. Only when the value arrives at runtime do you get a panic (behavior here might differ between compiler modes and on the playground).
Activity 7: Hand-coding challenge
In this activity you will hand-write two small functions that work out what someone pays at a check-out counter, given the sticker price, the sales tax, and whether they have a membership card worth 10% off.
Part 1 - Hand-coding on your own
You need to write your own sheet up but can work side-by-side.
You are writing two functions. main is written for you at the bottom, and it only ever calls print_receipt.
print_receipt takes the sticker price, the tax rate, and whether the customer has a membership card. It prints the receipt below, and returns nothing.
The rule: print_receipt does no arithmetic. No multiplying, no subtracting. Every number it prints either arrived as a parameter or came back from the other function.
The other function does all of the arithmetic. You decide what to call it, what it takes, and what it hands back.
A function can only return one value, but that value can be a tuple, so it can carry several numbers back at once.
Design it so that print_receipt has everything it needs.
Example, for print_receipt(100.00, 0.08, true):
Original: $100.00
Tax: $8.00
Discount: $10.80
Total: $97.20
Start with the function that does the arithmetic, since print_receipt has to call it.
#![allow(unused)] fn main() { fn ____________(______________________) -> ____________ { // Your implementation here } }
Now print_receipt, which calls the function you just designed. Does it need a return type?
#![allow(unused)] fn main() { fn print_receipt(______________________) ________ { // Your implementation here } }
main is written for you. You do not need to change it, but just notice what it calls.
fn main() { print_receipt(100.00, 0.08, true); print_receipt(100.00, 0.08, false); print_receipt(0.02, 0.08, true); }
Things to think about:
- Did your function hand back anything
print_receiptdid not actually need? - Does it matter in what order the tax and discount are applied?
- What would happen if the sticker price were very low (like 2 cents), or negative?
Part 2 - Swap for feedback
If you worked with someone, get feedback from a different person!
When I announce, you'll swap papers with a neighbor and look at their solution. Take a minute to give them feedback including:
- Any highlights of what they did well
- Any bugs you notice
- Any style feedback
At the end, I will collect papers and pick a couple (anonymized) to show on the screen for discussion.
Solutions
One possible solution:
#![allow(unused)] fn main() { fn calculate_totals(price: f64, tax_rate: f64, has_card: bool) -> (f64, f64, f64) { let tax = price * tax_rate; let subtotal = price + tax; let discount = if has_card { subtotal * 0.1 } else { 0.0 }; let final_price = subtotal - discount; (tax, discount, final_price) } fn print_receipt(price: f64, tax_rate: f64, has_card: bool) { let (tax, discount, final_price) = calculate_totals(price, tax_rate, has_card); println!("Original: ${:.2}", price); println!("Tax: ${:.2}", tax); println!("Discount: ${:.2}", discount); println!("Total: ${:.2}", final_price); } }
print_receipt(100.00, 0.08, true) prints $100.00, $8.00, $10.80, $97.20.
This is one good answer, not the only one.
Alternatives:
- Returns the original price as a fourth value,
(price, tax, discount, total). Okay but redundant - Returns only the final price. Then
print_receipthas to work out the tax and the discount (technically violates design requirements) - Returns a subtotal as well. Harmless, but nothing on the receipt prints it
Notes:
- The tuple has to be destructured,
let (tax, discount, final_price) = ..., or reached into with.0,.1and.2 print_receipthas no return type, so it returns()- A
has_cardof false gives a discount of0.0, not a missing value. The tuple is the same shape either way - Tax then discount and discount then tax both give the same total (but different tax and discount values)
- The 2 cent case is interesting: tax is 0.0016 and discount 0.00216, so both print as 0.02. The receipt looks like it does not add up, because
{:.2}is hiding the complete values - A negative price runs but might not give sensible answers
Activity 8: Loops, Functions, and Variables
Your Names:
Part 1: What Does This Print?
Problem 1
#![allow(unused)] fn main() { let scores = [85, 92, 78]; for (i, score) in scores.iter().enumerate() { println!("Student {} scored {}", i, score); } }
Problem 2
#![allow(unused)] fn main() { let mut x = 0; for i in 1..=3 { x += i; } println!("{}", x); }
Problem 3
#![allow(unused)] fn main() { for i in (0..5).step_by(2) { if i == 2 { continue; } println!("{}", i); } }
Part 2: Quick Quiz
- Which is a correct function signature for a function
is_positivethat takes an integer and returns whether it's positive?
- What shell command lists all files in the current directory, including hidden files?
- What git command would you use to add all new and modified files to the staging area?
- What shell command would you use to move to your home directory?
Part 3: Fill-in-the-blanks
Problem 1
/// Returns the largest number in the array. fn find_max(numbers: [i32; 5]) -> _______ { let mut max = numbers[0]; for _______ in _______ { if _______ > max { max = _______; } } _______ } fn main() { let scores = [85, 92, 78, 96, 88]; let highest = find_max(_______); println!("Highest score: {}", highest); }
Problem 2
/// Counts the even numbers from 1 up to and including `limit`. fn count_even_numbers(limit: u32) -> u32 { let mut count = 0; for i in _______ { if i % 2 _______ { count _______; } } count } fn main() { let result = count_even_numbers(10); println!("Even numbers from 1 to 10: {}", _______); }
Problem 3
#![allow(unused)] fn main() { /// You start with a personal best of 100 and 3 lives. /// Each try uses up a life and raises your personal best by 25. /// Keep trying while your personal best is 210 or less and you still have lives. /// Then determine whether you got above 210, and then... can you look at the function signature and guess what you might return? fn try_to_set_a_high_score() -> u32 { let mut personal_best = 100; let mut lives_left = 3; _______ personal_best <= 210 _______ lives_left > 0 { personal_best _______ 25; // You get a little better every time! lives_left _______; println!("Score: {}, Lives left: {}", _______, _______); } _______ personal_best _______ { println!("High score achieved!"); } _______ { println!("Try again later"); } _______ } }
Part 4: Debug the Code
The line where you notice a bug is not always the line you change to fix it.
Problem 1 (3 bugs):
#![allow(unused)] fn main() { fn calculate_average(numbers: [f64]) -> f64 { // look here let mut sum = 0; for num in numbers { sum += num; // look here } sum / numbers.len() // look here } }
Bug 1: ________________________________________________
Fix 1: ________________________________________________
Bug 2: ________________________________________________
Fix 2: ________________________________________________
Bug 3: ________________________________________________
Fix 3: ________________________________________________
Problem 2:
#![allow(unused)] fn main() { let arr = [1, 2, 3]; for i in 0..arr.len() { arr[i] = arr[i] * 2; // look here } }
Bug: ________________________________________________
Fix: ________________________________________________
Problem 3 (2 bugs):
#![allow(unused)] fn main() { /// Find the first occurrence of an even number in the array. /// If there are no even numbers, return -1 instead fn find_first_even(numbers: [u32; 5]) -> u32 { for num in numbers { if num % 2 = 0 { // look here return num; } } return -1; // look here } }
Bug 1: ________________________________________________
Fix 1: ________________________________________________
Bug 2: ________________________________________________
Fix 2: ________________________________________________
Solutions
Part 1: What Does This Print?
Problem 1
Student 0 scored 85
Student 1 scored 92
Student 2 scored 78
The index starts at 0.
Problem 2
6
Problem 3
0
4
Part 2: Quick Quiz
fn is_positive(n: i32) -> boolls -aorls -lagit add .(orgit add -A)cd ~
Part 3: Fill-in-the-blanks
Problem 1
Two correct answers here. Looping over the values:
fn find_max(numbers: [i32; 5]) -> i32 { let mut max = numbers[0]; for num in numbers { if num > max { max = num; } } max } fn main() { let scores = [85, 92, 78, 96, 88]; let highest = find_max(scores); println!("Highest score: {}", highest); }
Or looping over the indices (0..5 works too):
#![allow(unused)] fn main() { fn find_max(numbers: [i32; 5]) -> i32 { let mut max = numbers[0]; for i in 0..numbers.len() { if numbers[i] > max { max = numbers[i]; } } max } }
Problem 2
fn count_even_numbers(limit: u32) -> u32 { let mut count = 0; for i in 1..=limit { if i % 2 == 0 { count += 1; } } count } fn main() { let result = count_even_numbers(10); println!("Even numbers from 1 to 10: {}", result); }
Prints Even numbers from 1 to 10: 5
Problem 3
#![allow(unused)] fn main() { fn try_to_set_a_high_score() -> u32 { let mut personal_best = 100; let mut lives_left = 3; while personal_best <= 210 && lives_left > 0 { personal_best += 25; // You get a little better every time! lives_left -= 1; println!("Score: {}, Lives left: {}", personal_best, lives_left); } if personal_best > 210 { println!("High score achieved!"); } else { println!("Try again later"); } personal_best } }
Three lives only gets to 175, so it prints "Try again later" and returns 175.
Part 4: Debug the Code
Problem 1
Bug 1: Array parameter needs a size
Fix 1: fn calculate_average(numbers: [f64; 5]) -> f64
Bug 2: sum starts as an integer but gets floats added to it
Fix 2: let mut sum = 0.0;
Bug 3: sum is a float but numbers.len() is an integer
Fix 3: sum / (numbers.len() as f64)
Problem 2
Bug: Array needs to be mutable to modify its elements
Fix: let mut arr = [1, 2, 3];
Problem 3
Bug 1: if num % 2 = 0
Fix 1: if num % 2 == 0
Bug 2: Cannot return -1 from a function that returns u32 (unsigned)
Fix 2: Change the return type to i32. Then return num needs return num as i32, because num is still a u32 (or you could make the input parameter an array of i32 as well)
Activity 9: Big O Complexity Analysis
Instructions
For each problem below, write:
- Time complexity in Big O, for the worst case
- Space complexity in Big O: the extra memory the function uses, not counting its input
- Why, in one sentence
Problem 1: Array Sum
#![allow(unused)] fn main() { fn sum_array(arr: &[i32]) -> i32 { let mut total = 0; for &num in arr { total += num; } total } }
Time complexity: ________________
Space complexity: ________________
Why: ________________________________
Problem 2: Finding First Duplicate
#![allow(unused)] fn main() { fn find_first_duplicate(arr: &[i32]) -> Option<i32> { for i in 0..arr.len() { for j in (i+1)..arr.len() { if arr[i] == arr[j] { return Some(arr[i]); } } } None } }
Time complexity: ________________
Space complexity: ________________
Why: ________________________________
Problem 3: Tricky Loop
#![allow(unused)] fn main() { fn mystery(n: usize) -> usize { let mut count = 0; let mut remaining = n; while remaining > 0 { remaining /= 10; count += 1; } count } }
Time complexity: ________________
Space complexity: ________________
Why: ________________________________
Problem 4: Multiplying Grids
#![allow(unused)] fn main() { fn multiply_grids(a: &Vec<Vec<i32>>, b: &Vec<Vec<i32>>) -> Vec<Vec<i32>> { let n = a.len(); // both grids are n by n let mut result = vec![vec![0; n]; n]; for i in 0..n { for j in 0..n { for k in 0..n { result[i][j] += a[i][k] * b[k][j]; } } } result } }
Time complexity: ________________
Space complexity: ________________
Why: ________________________________
Bonus: Trading space for time
Both functions answer the same question: does this array have the same number in it twice? Every value in the array is less than 1,000.
Version A:
#![allow(unused)] fn main() { fn has_duplicates_a(arr: &[usize]) -> bool { for i in 0..arr.len() { for j in (i+1)..arr.len() { if arr[i] == arr[j] { return true; } } } false } }
Version B:
#![allow(unused)] fn main() { fn has_duplicates_b(arr: &[usize]) -> bool { let mut seen = [false; 1000]; for &value in arr { if seen[value] { return true; } seen[value] = true; } false } }
Version A:
- Time: _______ Space: _______
Version B:
- Time: _______ Space: _______
-
When might you prefer Version A?
-
When might you prefer Version B?
Solutions
Problem 1: O(n) time, O(1) space. One pass over the array, and only total is kept.
Problem 2: O(n^2) time, O(1) space. Nested loops over the array; worst case is no duplicate at all. Best case is O(1), when the first two numbers match.
Problem 3: O(log n) time, O(1) space. It counts the digits in n: each pass divides by 10, the bunnies in reverse. mystery(1,000) is 4 and mystery(1,000,000) is 7.
Problem 4: O(n^3) time, O(n^2) space. Three nested loops of n; the result is a new n by n grid.
Bonus, Version A: O(n^2) time, O(1) space.
Bonus, Version B: O(n) time. Space is always 1,000 true/false values no matter how long the array is: O(1) as the array grows, but it grows with the largest value allowed, the same as the sieve's O(limit).
- Prefer A when values could be huge (an array covering every possible value would be enormous), memory is tight, or the arrays are tiny
- Prefer B when arrays are long, values are small, and speed matters
Activity 10: Sorting Race
How it works
Each round is a race. Four people sort at the same time, each with their own cards and their own sort:
- Insertion sort
- Selection sort
- Merge sort
- Freestyle: any strategy you like, including "vibes"
The 5th person has a timer and lets everyone know when to start. When each person is done they say "done" and the timer notes down their time (but keeps the timer running until everyone is done!) then notes the results in the Google Form.
With a 6th person, they're the checker: they supervise to make sure folks are doing the right algorithm, and they check the cards are in order at the end.
Swap roles for round 2, so someone new is timing, and no one does the same algorithm twice.
The sorts, by hand
Lay your cards face up in a row, in the starting order.
Insertion sort. The leftmost card is your sorted row. Take the next card to its right and slide it left past every bigger card. Repeat until no cards are left.
Selection sort. Find the smallest card that isn't sorted yet. Move it to the end of your sorted row. Repeat.
Merge sort. Split the row into two piles. Keep splitting until every pile is one card. Then merge piles in pairs: look only at the smallest card of each pile, and take the smaller of the two. Keep merging until you have one pile.
The space below is for making notes, but you'll need to submit on the Google Form in the end!
Round 1: 8 cards
Starting order: 60 30 80 10 50 20 70 40
Which sort do you predict will win? ______________
| Sort | Sorter | Time (seconds) |
|---|---|---|
| Insertion | ||
| Selection | ||
| Merge | ||
| Freestyle |
Freestyle strategy:
Round 2: 16 cards
Starting order: 110 40 150 80 10 130 60 100 30 160 90 20 140 70 120 50
Which sort do you predict will win? ______________
| Sort | Sorter | Time (seconds) |
|---|---|---|
| Insertion | ||
| Selection | ||
| Merge | ||
| Freestyle |
Freestyle strategy:
While you wait
- Which sort felt easiest to do by hand? Which felt slowest? Why?
- A computer sorting 1,000,000 numbers: which of these sorts would you pick? Is that the same one that won for you?
Activity 11: Design a Struct for Real Data
Sheet A: weather stations
Odd groups. If your number is even, you want Sheet B.
Group members:
How this works
- Design, ~6 minutes. On this sheet, write:
- a struct for one row of your data, with a type for every field
- a separate struct for the whole collection, holding a
Vecof the first one - three method signatures, each marked
&selfor&mut self. One of them has to change something
- Write one method body, ~3 minutes. Real code if you can, pseudocode if you can't
- Swap sheets, ~4 minutes. Trade with a group that did the other task, and do the three jobs at the bottom of this sheet
A worked example, from a different data set
street species height_m healthy
Comm Ave maple 11.2 yes
Comm Ave oak 14.8 yes
Bay State Rd elm 6.4 no
#![allow(unused)] fn main() { struct Tree { species: String, height_m: f64, healthy: bool } struct Block { street: String, trees: Vec<Tree> } impl Block { /// Height of the tallest tree on the block, or 0.0 if there are none. fn tallest(&self) -> f64 { let mut tallest = 0.0; for tree in &self.trees { if tree.height_m > tallest { tallest = tree.height_m; } } tallest } } }
Your data: five stations report once an hour. Here is the 7am round:
station temp_f wind_mph precip_in sensor_ok
BOS-01 54.3 12.0 0.00 yes
BOS-02 51.9 8.5 0.12 yes
BOS-03 -999.0 0.0 0.00 no
BOS-04 49.7 15.2 0.31 yes
BOS-05 53.1 6.4 0.00 yes
Design a Reading for one row, and a DailyReport that holds a date and all the readings for that day.
Write this method: average_temp, on DailyReport. The average temperature across the day's readings.
Look at BOS-03 before you write it.
Before you design it
Your collection struct holds the date. Pull one row out of it and hand it to someone else. Does that row still know when it happened?
What else would you want on a row, and where would it come from?
Your design
Row struct:
Collection struct:
Three method signatures, each marked &self or &mut self:
The method body you were asked to write:
If you finish early
- What else would be useful on
Readingitself? One example: the temperature in Celsius. Write the signature and a line of pseudocode for the body - Grouping by day is one choice. What else could you group by? You might want one station followed over time, with summary statistics of its own. Sketch that struct: what does it hold, and what methods would it have?
When you get the other group's sheet
Write on their sheet, and sign your group number.
- Check every
&selfand&mut self. Mark any you disagree with and why - Add one other method that could be useful. Get creative! Signature, the right
self, and a line of pseudocode saying what the body does - Name one field whose type you'd change, and say why
Sheet B: shuttle trips
Even groups. If your number is odd, you want Sheet A.
Group members:
How this works
- Design, ~6 minutes. On this sheet, write:
- a struct for one row of your data, with a type for every field
- a separate struct for the whole collection, holding a
Vecof the first one - three method signatures, each marked
&selfor&mut self. One of them has to change something
- Write one method body, ~3 minutes. Real code if you can, pseudocode if you can't
- Swap sheets, ~4 minutes. Trade with a group that did the other task, and do the three jobs at the bottom of this sheet
A worked example, from a different data set
street species height_m healthy
Comm Ave maple 11.2 yes
Comm Ave oak 14.8 yes
Bay State Rd elm 6.4 no
#![allow(unused)] fn main() { struct Tree { species: String, height_m: f64, healthy: bool } struct Block { street: String, trees: Vec<Tree> } impl Block { /// Height of the tallest tree on the block, or 0.0 if there are none. fn tallest(&self) -> f64 { let mut tallest = 0.0; for tree in &self.trees { if tree.height_m > tallest { tallest = tree.height_m; } } tallest } } }
Your data: one row per shuttle arrival. Times are minutes after midnight, so 8:05am is 485:
route stop scheduled_min actual_min riders
CommAve Kenmore Sq 485 489 31
CommAve Silber Way 492 492 44
1BU Danielsen Hall 495 493 12
CommAve Marsh Plaza 500 514 58
1BU Agganis Way 505 507 7
Design a Trip for one row, and a ServiceDay that holds a date and all of the day's trips.
Write this method: late_count, on ServiceDay. How many trips arrived more than threshold minutes after they were scheduled. It takes threshold as a second parameter, after self.
Look at the Danielsen trip before you write it.
Before you design it
Your collection struct holds the date. Pull one row out of it and hand it to someone else. Does that row still know when it happened?
What else would you want on a row, and where would it come from?
Your design
Row struct:
Collection struct:
Three method signatures, each marked &self or &mut self:
The method body you were asked to write:
If you finish early
- What else would be useful on
Tripitself? One example: the scheduled time as hours and minutes, so 485 reads as 8:05. Write the signature and a line of pseudocode for the body - Grouping by day is one choice. What else could you group by? You might want one route followed over time, with summary statistics of its own. Sketch that struct: what does it hold, and what methods would it have?
When you get the other group's sheet
Write on their sheet, and sign your group number.
- Check every
&selfand&mut self. Mark any you disagree with and why - Add one other method that could be useful. Get creative! Signature, the right
self, and a line of pseudocode saying what the body does - Name one field whose type you'd change, and say why
Solutions
Sheet A: weather stations
struct Reading {
station: String,
temp_f: f64,
wind_mph: f64,
precip_in: f64,
sensor_ok: bool,
}
struct DailyReport {
date: String,
readings: Vec<Reading>,
}
Sheet A: average_temp
impl DailyReport {
fn average_temp(&self) -> f64 {
let mut sum = 0.0;
let mut count = 0;
for r in &self.readings {
if !r.sensor_ok { continue; }
sum += r.temp_f;
count += 1;
}
if count == 0 { 0.0 } else { sum / count as f64 }
}
fn add_reading(&mut self, r: Reading) {
self.readings.push(r);
}
}
BOS-03 reports -999.0. If you skip it the average will be 52.25, but if you include it you'll get -158.0.
Sheet B: shuttle trips
One row per shuttle arrival
struct Trip {
route: String,
stop: String,
scheduled_min: u32,
actual_min: u32,
riders: u32,
}
struct ServiceDay {
date: String,
trips: Vec<Trip>,
}
Sheet B: late_count
impl ServiceDay {
fn late_count(&self, threshold: u32) -> u32 {
let mut count = 0;
for t in &self.trips {
if t.actual_min > t.scheduled_min + threshold {
count += 1;
}
}
count
}
fn add_trip(&mut self, t: Trip) {
self.trips.push(t);
}
}
The finish-early prompts. Celsius is fn temp_c(&self) -> f64 { (self.temp_f - 32.0) * 5.0 / 9.0 }. Hours and minutes is fn scheduled_hm(&self) -> (u32, u32) { (self.scheduled_min / 60, self.scheduled_min % 60) }, or a String. Both go on the row struct, not the collection: the method lives on whichever type holds the data it needs.
Before you design it. Neither Reading nor Trip carries a date (only the collection holds it). Both answers are defensible though. A date on every row adds lots copies of the same string, but no date means a row is not a standalone piece of info.
Another way to group it. StationHistory { station: String, readings: Vec<Reading> } with something like max_temp or hours_offline, or RouteHistory { route: String, trips: Vec<Trip> } with on_time_rate. This relates to the last question: when you want to regroup by station instead of by day, every Reading needs to know its own hour and date.
Activity 12: Write the Match
How this works
The problems are on this paper, but you'll work through the problems in Rust Playground, and the finished functions go to Gradescope.
- Open play.rust-lang.org
- For each problem, copy the type (struct/enum) and the function signature into the playground
- Write the
matchthat makes the function produce the results in the table - Write a
fn mainthat calls it with the examples, and check you get what the table says - Paste your finished functions into the Gradescope assignment
Work with the people around you. But you'll submit individually.
A worked example
The problem gives you this:
enum Coin { Penny, Nickel, Dime }
fn value(c: Coin) -> u32 {
// your code here
}
| Call | Returns |
|---|---|
value(Coin::Penny) | 1 |
value(Coin::Dime) | 10 |
You write the body, and a main to check it:
enum Coin { Penny, Nickel, Dime } fn value(c: Coin) -> u32 { match c { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, } } fn main() { println!("{}", value(Coin::Penny)); println!("{}", value(Coin::Dime)); }
When you run it, if it prints 1 and 10, the problem is done.
Problem 1: Which way are we going
enum Direction { North, East, South, West }
fn label(dir: Direction) -> String {
// your code here
}
| Call | Returns |
|---|---|
label(Direction::North) | "going north" |
label(Direction::East) | "going east" |
label(Direction::South) | "going south" |
label(Direction::West) | "going west" |
Problem 2: A score that might not exist
fn describe(score: Option<u32>) -> String {
// your code here
}
Tip: to return an owned string you can use format! instead of println! to create a string with variable values. And to make a String out of a "string literal" like "hello" you need to use "hello".to_string().
| Call | Returns |
|---|---|
describe(Some(95)) | "scored 95" |
describe(Some(0)) | "scored 0" |
describe(None) | "did not take it" |
Problem 3: Class standing
Match on a struct, ignoring the fields you don't need.
struct Student {
name: String,
year: u32,
credits: u32,
}
fn standing(s: &Student) -> String {
// your code here
}
| Call | Returns |
|---|---|
standing(&Student { name: String::from("Kesar"), year: 3, credits: 96 }) | "senior" |
| a student with 72 credits | "junior" |
| a student with 30 credits | "sophomore" |
| a student with 12 credits | "first year" |
Senior is 90 credits or more, junior 60, sophomore 30.
Problem 4: Adding up to n
You'll use recursion here. You'll write a match with a base case and a recursive call.
fn sum_to(n: u32) -> u32 {
// your code here
}
sum_to(4) is 4 + 3 + 2 + 1 + 0.
| Call | Returns |
|---|---|
sum_to(0) | 0 |
sum_to(4) | 10 |
sum_to(10) | 55 |
Problem 5: The first even number
This one is more challenging. This needs a loop as well as a match, and it returns an Option.
fn first_even(nums: [u32; 5]) -> Option<u32> {
// your code here
}
| Call | Returns |
|---|---|
first_even([1, 3, 6, 7, 8]) | Some(6) |
first_even([2, 4, 6, 8, 10]) | Some(2) |
first_even([1, 3, 5, 7, 9]) | None |
Solutions
Problem 1: Direction
fn label(dir: Direction) -> String {
match dir {
Direction::North => String::from("going north"),
Direction::East => String::from("going east"),
Direction::South => String::from("going south"),
Direction::West => String::from("going west"),
}
}
Four arms, one per variant, and no _ needed. The return type is String, so we need this or "going north".to_string() technically.
Problem 2: a score that might not exist
fn describe(score: Option<u32>) -> String {
match score {
Some(n) => format!("scored {}", n),
None => "did not take it".to_string(),
}
}
Some(n) names the number so you can use it on the right. Two arms covers the whole type: an Option has nothing else in it.
Problem 3: class standing
fn standing(s: &Student) -> String {
match s {
&Student { credits, .. } if credits >= 90 => String::from("senior"),
&Student { credits, .. } if credits >= 60 => String::from("junior"),
&Student { credits, .. } if credits >= 30 => String::from("sophomore"),
_ => String::from("first year"),
}
}
Biggest number first. Put >= 30 at the top and every senior is a sophomore.
.. ignores name and year. The & is there because s is a &Student.
Problem 4: adding up to n
fn sum_to(n: u32) -> u32 {
match n {
0 => 0,
_ => n + sum_to(n - 1),
}
}
The base case is the arm that does not call itself. Without it, n - 1 runs past zero and a u32 cannot go negative.
Problem 5: the first even number
fn first_even(nums: [u32; 5]) -> Option<u32> {
for n in nums {
match n % 2 {
0 => return Some(n),
_ => {}
}
}
None
}
return leaves the whole function the moment you find one. None sits after the loop, for when it finishes without finding anything.
Activity 13: Error Handling by Hand
Name:
1. The empty list problem
On Monday we wrote average for the grade tracker, and gave it a bad answer for a student with no grades yet:
fn average(&self) -> f64 {
if self.grades.len() == 0 {
return 0.0; // an average of zero? they have no grades
}
let mut total = 0.0;
for grade in &self.grades {
total += grade;
}
total / self.grades.len() as f64
}
A student with no grades and a student failing everything both come back as 0.0. Nothing that calls this can tell them apart.
(a) Fill in a return type that can say "there is no average yet", and rewrite the body to match.
fn average(&self) -> ______________ {
}
(b) You had a choice here for your return type. What did you pick and why?
2. Error Propagation with match
- Use this helper function to complete
parse_and_double - The helper function handles parsing and returns clear error messages
// Helper function (already written for you):
fn parse_int(input: &str) -> Result<i32, String> {
match input.parse::<i32>() {
Ok(num) => Ok(num),
Err(_) => Err(format!("'{}' is not a valid number", input)),
}
}
// Complete this function using the helper:
fn parse_and_double(input: &str) -> Result<i32, String> {
let num = match parse_int(input) {
___________ => ___________,
___________ => ___________,
};
let doubled = ___________;
_____________
}
3. Using the ? operator
- Rewrite the parse_and_double function using the
?operator - Use the same helper function from problem 2
fn parse_and_double_short(input: &str) -> Result<i32, String> {
// Your code here (should be 2-3 lines)
}
Solutions
Problem 1: The empty list problem
fn average(&self) -> Option<f64> {
if self.grades.len() == 0 {
return None;
}
let mut total = 0.0;
for grade in &self.grades {
total += grade;
}
Some(total / self.grades.len() as f64)
}
Part (b) Option is the better fit but Result is defensible:
Optionsays there is no average. A student with no grades yet is not an error, it is a normal state at the start of term. There is nothing to report to anyoneResult<f64, String>works and will compile, but it forces you to invent an error message for something that has not gone wrong
Problem 2: Error Propagation with match
Several alternatives to parse_and_double:
fn parse_and_double(input: &str) -> Result<i32, String> {
let num = match parse_int(input) {
Ok(n) => n,
Err(e) => return Err(e),
};
let doubled = num * 2;
Ok(doubled)
}
Or having both arms of the match "do" something:
fn parse_and_double(input: &str) -> Result<i32, String> {
let mut num = 0; // can also just say `let mut num` but we haven't covered that
match parse_int(input) {
Ok(n) => num = n,
Err(e) => return Err(e),
};
let doubled = num * 2;
Ok(doubled)
}
Or letting the whole match just be an expression so that's what gets returned:
fn parse_and_double(input: &str) -> Result<i32, String> {
match parse_int(input) {
Ok(n) => Ok(n*2),
Err(e) => Err(e),
}
}
Problem 3: Using the ? operator
Which leads us to the most concise versions with ?:
fn parse_and_double(input: &str) -> Result<i32, String> {
let num = parse_int(input)?;
Ok(num * 2)
}
Or even shorter:
fn parse_and_double(input: &str) -> Result<i32, String> {
Ok(2*parse_int(input)?)
}
Activity 14: Confidence check
Name:
Midterm 1 is Friday. This week you also sit down with a CA and talk about your Project 1 code.
This sheet is not a quiz. You don't actually answer anything. Just read each line and mark how you feel about it, then keep the paper and study from the third column.
Mark one box per row:
- Got it. I could do this right now, on paper, with nobody helping.
- Shaky. I would get there, but I would be slow or I would second-guess it.
- Study it. I need to go back to this before Friday.
Everything here is from Lectures 1 through 13. Nothing new from today's lecture (L14) is on the midterm.
Part 1: Tools
| Could you do this? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 1.1 | Move into a directory and list everything in it, hidden files included | |||
| 1.2 | Rename a file, then delete it | |||
| 1.3 | Send a command's output into a file instead of the screen | |||
| 1.4 | See what you have changed but not yet staged in git | |||
| 1.5 | Make a branch, commit on it, and push it | |||
| 1.6 | Undo a commit that is already pushed | |||
| 1.7 | Say how cargo build is different than rustc, and what --release changes |
Part 2: Rust, line by line
| Could you do this? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 2.1 | Make a variable changeable | |||
| 2.2 | Shadow a variable | |||
| 2.3 | Define a constant | |||
| 2.4 | Find the largest value of an i8 and a u8 | |||
| 2.5 | Say what could happen when an i32 addition goes past its maximum | |||
| 2.6 | Say why you cannot add a u32 to an i32, and what to do about it | |||
| 2.7 | Write a function that hands back two values at once | |||
| 2.8 | Say whether something is a statement or an expression | |||
| 2.9 | Pick between loop, while, and for, and defend your choice | |||
| 2.10 | Break out of a loop, and skip to the next pass through it | |||
| 2.11 | Choose between &self, &mut self, and self on a method | |||
| 2.12 | Write a constructor, and say why it is Thing::new and not thing.new | |||
| 2.13 | Say what the compiler does when a match misses a variant | |||
| 2.14 | Use Option instead of a stand-in value like -1 | |||
| 2.15 | Choose between panic! and returning a Result, and defend the choice | |||
| 2.16 | Use ?, and say what it needs from the function's return type |
Part 3: Read the code
Again, don't answer these completely - just decide whether you could.
3.1 What does this print?
#![allow(unused)] fn main() { let x = 5; let x = x + 1; { let x = x * 2; println!("inner: {x}"); } println!("outer: {x}"); }
3.2 Does this compile? If not, what is the error and what is the fix?
#![allow(unused)] fn main() { let a: u32 = 5; let b: i32 = 3; println!("{}", a + b); }
3.3 Does this compile? If not, what is the error and what is the fix?
#![allow(unused)] fn main() { fn double(n: i32) -> i32 { n * 2; } }
3.4 What does this print?
#![allow(unused)] fn main() { let scores = [90, 75, 88, 62]; let mut total = 0; for s in scores { if s < 80 { continue; } total += s; } println!("{total}"); }
| Got it | Shaky | Study it | |
|---|---|---|---|
| 3.1 | |||
| 3.2 | |||
| 3.3 | |||
| 3.4 |
Part 4: Write it from nothing
On paper, no compiler, no notes. Could you do it?
| Could you write this? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 4.1 | Given struct Counter { hits: u32 }, a method that adds one to hits and a method that reports whether hits is over 10 | |||
| 4.2 | A recursive function that adds up the digits of a u32 | |||
| 4.3 | An enum for a traffic light where one variant carries a number of seconds, and a match over it | |||
| 4.4 | A function that divides two numbers and gives back a Result, with an error when the divisor is zero |
Part 5: Say it out loud
| Could you explain this to someone? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 5.1 | Why merge sort is O(n log n) | |||
| 5.2 | What's the difference between a compiled and an interpreted language | |||
| 5.3 | Why we don't distinguish O(3n^2 + 500n) from O(n^2) | |||
| 5.4 | How many bits are in a byte | |||
| 5.5 | What every recursive function needs, and what happens without it |
Part 6: Prep and reflect
Some things to reflect on.
1. Which part of your Project 1 would you least like to be asked about this week? (And what can you do to prepare?)
2. Of everything you marked "Study it", which do you think will be more important to review?
Before you go
Take a photo of both sides and upload it. Then keep the paper so it can help guide your studying.
Solutions
One-line answers. If yours is longer and says the same thing, it is right.
Part 1
- 1.1
cd dir, thenls -a.ls -laalso shows permissions and sizes - 1.2
mv old.txt new.txtto rename, thenrm new.txtto delete.mvdoes double duty as rename and move - 1.3
command > out.txt. A single>replaces the file,>>adds to the end of it - 1.4
git diff. Staged changes aregit diff --staged, andgit statusnames the files without showing the contents - 1.5
git switch -c name, commit, thengit push -u origin name. The-uis what makes later pushes on that branch justgit push - 1.6
git revert <hash>, which makes a new commit undoing that one. Safer than deleting history, because anyone who already pulled still has a history that matches yours - 1.7
cargoreadsCargo.toml, fetches your dependencies, and builds the whole project;rustccompiles the one file you point it at.--releaseturns on optimization, so it compiles slower and runs faster
Part 2
- 2.1
let mut x = 5; - 2.2 Write
letagain with the same name:let x = x + 1;. That is a new variable, and it is allowed to have a different type.mutinstead keeps one variable and changes its value - 2.3
const MAX_TRIES: u32 = 10;. Needs the type written out, has to be a value known at compile time, and is conventionally SCREAMING_CASE - 2.4
i8tops out at 127,u8at 255. Both hold 256 values, buti8spends half its range on negatives - 2.5 Two different things depending on the build. Debug panics with "attempt to add with overflow"; release wraps around silently. Same code, two behaviors
- 2.6 Rust does no implicit numeric conversion. Cast with
as, or declare both the same type.ascan lose information, so it is a choice you are making on purpose - 2.7 Return a tuple:
-> (u32, u32), then(a, b). Destructure at the call site withlet (x, y) = ... - 2.8 An expression evaluates to a value; a statement does not. A trailing semicolon turns an expression into a statement, so the value is thrown away
- 2.9
forwhen you know the collection or the count,whilewhen you have a condition,loopwhen you willbreakout yourself - 2.10
breakleaves the loop,continuejumps to the next pass - 2.11
&selfto read,&mut selfto change,selfto consume. A method that changes the struct and is declared&selfwill not compile - 2.12
fn new(...) -> Self, with noselfparameter, so it is an associated function rather than a method.::because there is no instance yet to put on the left of a dot - 2.13 It refuses to compile, and names the variant you missed. That is the payoff of an enum: add a variant and the compiler finds every
matchthat now needs updating - 2.14
Option<T>makes "nothing" a separate case the compiler forces you to handle.-1is a real number that happens to mean something else, and it can be used by accident - 2.15 Panic when the situation is a bug in your own code and carrying on makes no sense. Return a
Resultwhen the caller could reasonably recover, such as a missing file or bad input - 2.16
?hands back the value on success, and on failure returns the error out of the current function. So the function itself has to returnResultorOption
Part 3
- 3.1
inner: 12, thenouter: 6. The first shadow makesx6; the inner block shadows again to 12, and that binding ends with the block - 3.2 No. Mismatched types on
a + b. Cast,a + b as u32, or declare both the same type. Noteb as u32would wrap ifbwere negative - 3.3 No.
expected i32, found (). The semicolon aftern * 2throws the value away. Delete it, or writereturn n * 2; - 3.4
178. 90 and 88 are added, 75 and 62 are skipped
Part 4
- 4.1
fn bump(&mut self) { self.hits += 1; }andfn is_hot(&self) -> bool { self.hits > 10 }. The point is the two different receivers - 4.2 Base case
if n < 10 { return n; }, thenn % 10 + digit_sum(n / 10) - 4.3
enum Light { Red, Green, Yellow(u32) }, then amatchwith aLight::Yellow(secs) =>arm binding the payload. Missing a variant is a compile error - 4.4
fn divide(a: f64, b: f64) -> Result<f64, String>, returningErr(...)whenb == 0.0andOk(a / b)otherwise
Part 5
- 5.1 The call tree has log n levels, because the list halves each time, and every level does n work merging back together. n per level times log n levels
- 5.2 A compiler translates the whole program to machine code once, ahead of time, and can optimize across the whole thing. An interpreter works out what to do line by line every time it runs
- 5.3 Constants drop and lower-order terms drop, because for large enough n the n^2 term is what decides the answer. At n = 1000 the n^2 term is 3,000,000 and the other is 500,000
- 5.4 Eight
- 5.5 A base case that returns without recursing, and a call that moves toward it. Without both, it recurses until the stack runs out
Part 6 has no answers. It is reflection, and question 2 is the one to aim your studying with.
Activity 15: Hand-coding, together
Names:
Try to solve this like real exam problem, without referring to notes or tech. This is what the hand-coding section of Friday's exam will feel like (except for the working together part). Take turns writing.
General advice: Start with the function signatures, think about inputs and outputs and the overall logic, then work on the details and syntax as you have time.
Problem 1: What is this card worth
We are scoring a card game. A card reaches us in one of three forms.
#![allow(unused)] fn main() { enum Card { Face(char), Number(u32), Joker, } }
Write a function value that says what a card is worth. The rules:
- A
Facecard is worth 10 for'J','Q', and'K', and 11 for'A'. - A
Numbercard is worth what it says, as long as it is between 2 and 10 (inclusive). - A
Jokeris worth 0 - Any other Face or Number card with an invalid char or u32 is worth
None
*Remember!! the compiler doesn't know about your card deck, so you have to account for every possible value of Card that is conceivable.
#![allow(unused)] fn main() { fn value(c: Card) -> Option<u32> { } }
When you are done: somebody adds a fourth variant, Card::Wild. What does the compiler do to your function as is? What would you have to adjust?
Problem 2: Points per game
A player's points from each game they have played are in a Vec. Write a function that gives back their average. There is no sensible average of no games, so complain rather than guess in that case.
#![allow(unused)] fn main() { fn points_per_game(points: &Vec<u32>) -> Result<f64, String> { } }
Then, when called, print the average if there is one, and print the error message if there is not. Write that logic here in main:
fn main() { let points = vec![22, 31, 18, 27, 19]; }
When you are done: check your division. Are you sure you'll get a decimal like 23.4 and not 23?
Solutions
Problem 1
#![allow(unused)] fn main() { fn value(c: Card) -> Option<u32> { match c { Card::Face('J') | Card::Face('Q') | Card::Face('K') => Some(10), Card::Face('A') => Some(11), Card::Face(_) => None, Card::Number(n) if n >= 2 && n <= 10 => Some(n), Card::Number(_) => None, Card::Joker => None, } } }
or something like
#![allow(unused)] fn main() { fn value(c: Card) -> Option<u32> { match c { Card::Face('J') => Some(10), Card::Face('Q') => Some(10), Card::Face('K') => Some(10), Card::Face('A') => Some(11), Card::Number(n) if n >= 2 && n <= 10 => Some(n), _ => None, } } }
but that has the disadvantage of not noticing if a new card type was added to the enum (and you might want the compiler to fail here to alert you!)
Problem 2
fn points_per_game(points: &Vec<u32>) -> Result<f64, String> { if points.len() == 0 { return Err("no games played".to_string()); } let mut total = 0; for p in points { total += p; } Ok(total as f64 / points.len() as f64) } fn main() { let points = vec![22, 31, 18, 27, 19]; match points_per_game(&points) { Ok(a) => println!("{a}"), Err(e) => println!("{e}"), } }
Activity 17: My First Stack
Name:
Problems 1 and 2 we do together during lecture. Problems 3 and 4 are at the end. Hand this in on your way out.
How to draw a stack
- One box per function call, stacked bottom to top, with
mainat the bottom - Inside each box, list the variables that call has: parameters first, then locals
- Write the type next to every variable.
x: i32, not justx - A frame holds every variable its function declares, from the moment the function is called. Write
???for any that has not been given a value yet (this includes return values!) - A
{ }block inside a function gets a mini-frame: a dashed box stacked on top of its function's frame, popped off at the closing brace - To find a variable, read from the top down and stop at a solid line. (A dashed line connecting a frame and mini-frame can been seen through.)
Problem 1
fn main() { let a = 1; let b = add_one(a); println!("{}", b); } fn add_one(n: i32) -> i32 { let result = n + 1; // DRAW HERE result }
Problem 2
Careful, this one has a scope inside a function.
fn main() { let mut total = 10; { let bonus = 5; let doubled = bonus * 4; total = total + bonus + doubled / 4; // DRAW HERE } println!("{}", total); }
After the closing brace, which of these still exist?
Problem 3
fn main() { let n = 3; let answer = outer(n); println!("{}", answer); } fn outer(x: i32) -> i32 { let y = inner(x * 2); let z = y + 1; z } fn inner(v: i32) -> i32 { let w = v * 2; // DRAW HERE w }
Problem 4
We walked through this example in Lecture 10, with a name for every value this time. Now let's draw it on the stack.
fn sum_to(n: u64) -> u64 { if n == 0 { let base = 0; // DRAW HERE return base; } let rest = sum_to(n - 1); let sum = n + rest; sum } fn main() { let total = sum_to(3); println!("{}", total); }
How many frames are on the stack at the deepest point of sum_to(1000)?
Solutions
Problem 1
┌──────────────────────────┐
│ add_one │
│ n: i32 = 1 │
│ result: i32 = 2 │
└──────────────────────────┘
┌──────────────────────────┐
│ main │
│ a: i32 = 1 │
│ b: i32 = ??? │
└──────────────────────────┘
Problem 2
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ bonus: i32 = 5 ╎
╎ doubled: i32 = 20 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ total: i32 = 20 │
│ (was 10) │
└──────────────────────────┘
After the closing brace, only total still exists, and it is still 20. bonus and doubled popped off with the mini-frame.
Problem 3
┌──────────────────────────┐
│ inner │
│ v: i32 = 6 │
│ w: i32 = 12 │
└──────────────────────────┘
┌──────────────────────────┐
│ outer │
│ x: i32 = 3 │
│ y: i32 = ??? │
│ z: i32 = ??? │
└──────────────────────────┘
┌──────────────────────────┐
│ main │
│ n: i32 = 3 │
│ answer: i32 = ??? │
└──────────────────────────┘
Problem 4
┌──────────────────────────┐
│ sum_to │
│ n: u64 = 0 │
│ base: u64 = 0 │
│ rest: u64 = ??? │
│ sum: u64 = ??? │
└──────────────────────────┘
┌──────────────────────────┐
│ sum_to │
│ n: u64 = 1 │
│ base: u64 = ??? │
│ rest: u64 = ??? │
│ sum: u64 = ??? │
└──────────────────────────┘
┌──────────────────────────┐
│ sum_to │
│ n: u64 = 2 │
│ base: u64 = ??? │
│ rest: u64 = ??? │
│ sum: u64 = ??? │
└──────────────────────────┘
┌──────────────────────────┐
│ sum_to │
│ n: u64 = 3 │
│ base: u64 = ??? │
│ rest: u64 = ??? │
│ sum: u64 = ??? │
└──────────────────────────┘
┌──────────────────────────┐
│ main │
│ total: u64 = ??? │
└──────────────────────────┘
Each call has its own n, and only the top one is running: the other three are each waiting on let rest = sum_to(n - 1). Since base is declared inside the if block's braces, drawing it in a dashed mini-frame on top of the n = 0 frame instead is also right.
After this, base of 0 goes into the n = 1 frame's rest, its sum is 1, that goes into the n = 2 frame's rest, and so on until total is 6.
sum_to(1000) at its deepest point has 1,002 frames: main, plus one sum_to frame for every n from 1000 down to 0, which is 1,001 of them. Each is small, but a big enough n runs the stack out of room, which is how a stack overflow happens.
Activity 18: Stack and Heap Diagram Practice
Name:
Problems 1 and 2 we do together during lecture. Problem 3 is at the end, and Problem 4 is for if you finish early. Hand this in on your way out.
Instructions
For each code snippet below:
- Draw the stack and heap at the moment marked
// DRAW HERE - Stack on the left, heap on the right, and build the stack from the bottom up
- Label every variable with its type, and give
StringandVectheirlenandcap - Draw an arrow from each pointer to the thing it points at
- Box each stack frame separately and label it with the function name
- A frame holds every variable its function declares, from the start. Write
???for any with no value yet, return values included, before you draw the frame above it
Common mistakes
- Leaving the types off. Half the information in the diagram is in the types
- Forgetting
lenandcaponStringandVec - Drawing the characters of a
Stringon the stack - Drawing a
Vec's elements on the stack. An array's go there; aVec's do not
Problem 1 (in lecture)
Concepts: an array, a Vec, and a String, side by side
fn main() { let a = [1, 2, 3]; let v = vec![1, 2, 3]; let s = String::from("hi"); // DRAW HERE println!("{:?} {:?} {}", a, v, s); }
Problem 2 (in lecture)
Concepts: a String on the heap, a string literal in the program, two frames
fn main() { let name = String::from("Bob"); let age = 5; print_label("Age", age); println!("{}", name); } fn print_label(label: &str, value: i32) { // DRAW HERE println!("{}: {}", label, value); }
Problem 3
Concepts: a Vec of Vecs, heap pointing at heap
fn main() { let grid = vec![vec![1, 2], vec![3, 4], vec![5, 6]]; // DRAW HERE println!("{:?}", grid); }
Are 2 and 3 next to each other in memory? Are 1 and 2?
Problem 4: if you finish early
How many bytes does each of these take on the stack? Guess first, then reason it out.
i32 ________ [i32; 3] ________ String ________
Vec<i32> ________ Vec<String> ________ &str ________
Why are String, Vec<i32>, and Vec<String> all the same size?
Solutions
Problem 1
Stack: Heap:
┌────────────────────────────┐
│ main │
│ a: [i32; 3] = [1, 2, 3] │
│ v: Vec<i32> │ ┌───┬───┬───┐
│ ptr ───────────────────┼───────▶│ 1 │ 2 │ 3 │
│ len: 3, cap: 3 │ └───┴───┴───┘
│ s: String │ ┌─────┬─────┐
│ ptr ───────────────────┼───────▶│ 'h' │ 'i' │
│ len: 2, cap: 2 │ └─────┴─────┘
└────────────────────────────┘
Problem 2
Stack:
┌──────────────────────────┐
│ print_label │ Program binary:
│ label: &str │ ┌─────┬─────┬─────┐
│ ptr ─────────────────┼───────▶│ 'A' │ 'g' │ 'e' │
│ len: 3 │ └─────┴─────┴─────┘
│ value: i32 = 5 │
└──────────────────────────┘
┌──────────────────────────┐
│ main │ Heap:
│ name: String │ ┌─────┬─────┬─────┐
│ ptr ─────────────────┼───────▶│ 'B' │ 'o' │ 'b' │
│ len: 3, cap: 3 │ └─────┴─────┴─────┘
│ age: i32 = 5 │
└──────────────────────────┘
Problem 3
Stack: Heap:
┌───────────────────────┐ ┌────────────────┐ ┌───┬───┐
│ main │ ┌──▶│ ptr ───────────┼───────▶│ 1 │ 2 │
│ grid: Vec<Vec<i32>> │ │ │ len: 2, cap: 2 │ └───┴───┘
│ ptr ──────────────┼──────┘ ├────────────────┤ ┌───┬───┐
│ len: 3, cap: 3 │ │ ptr ───────────┼───────▶│ 3 │ 4 │
└───────────────────────┘ │ len: 2, cap: 2 │ └───┴───┘
├────────────────┤ ┌───┬───┐
│ ptr ───────────┼───────▶│ 5 │ 6 │
│ len: 2, cap: 2 │ └───┴───┘
└────────────────┘
Are 2 and 3 next to each other? No. They are in different blocks. Are 1 and 2? Yes: they are the two elements of the first inner Vec, side by side in one block.
Problem 4
| Type | Bytes on the stack | Why |
|---|---|---|
i32 | 4 | 32 bits |
[i32; 3] | 12 | Three i32s, right in the frame |
String | 24 | ptr, len, cap, 8 bytes each |
Vec<i32> | 24 | Same three fields |
Vec<String> | 24 | Same three fields |
&str | 16 | ptr and len, no cap |
String, Vec<i32>, and Vec<String> are all the same size because the stack only ever holds the handle, and the handle is three 8-byte numbers no matter what it points at.
Activity 19: Draw the Arrows, Then Poke at Them
Name:
Part 1 we do together during lecture. Part 2 is at the end, with a laptop. Hand this in on your way out.
Part 1: Draw the arrows
Stack on the left, heap on the right. Types on everything and arrows from references to what they point to.
Problem 1 (in lecture)
fn main() { let mut x = 10; let y = 20; let r1 = &y; let r2 = &mut x; *r2 = 15; // DRAW HERE }
Problem 2 (in lecture)
fn main() { let numbers = vec![10, 20, 30, 40]; let name = String::from("Alice"); let r1 = &numbers; let r2 = &numbers[1]; let r3 = &name; let r4: &str = "Bob"; // DRAW HERE }
Part 2: Poke at pointers
The code for each experiment is on the website version of this page: you can even press the Run button at the top right of the block, and edit it right there. Or copy it into Rust Playground.
Run it, write down what you see, then make the change and run it again. Addresses will be different from your neighbors'. The interesting part is which ones match and which ones are close.
Experiment 1: an arrow into another frame
fn with_bonus(points: &i32) -> i32 { println!("points holds {:p}", points); println!("points lives at {:p}", &points); let result = *points + 5; result } fn main() { let score = 10; println!("score lives at {:p}", &score); let total = with_bonus(&score); println!("score {score}, total {total}"); }
a. Which two addresses match? Why?
b. points lives somewhere too. Is its address close to score's, or far away? Where is it?
c. Change it: add the line *points += 5; inside with_bonus, to change score directly. What does the compiler complain about, in your own words?
Experiment 2: watch a Vec move
fn main() { let mut v: Vec<i32> = Vec::new(); for i in 0..20 { v.push(i); println!("len {:2} cap {:2} data at {:p}", v.len(), v.capacity(), v.as_ptr()); } }
a. When does cap change? What is the pattern?
b. When does the data at address change? Why would the data move at all?
c. Change it: replace Vec::new() with Vec::with_capacity(20). What is different?
Experiment 3: break it on purpose
fn main() { let r: &i32; { let x = 5; r = &x; } println!("{r}"); }
a. This does not compile. Copy the first line of the error.
b. In your own words, what is the compiler worried about?
c. Change it: move the println! up, inside the braces. What happens?
Experiment 4, if you finish early: how big is an arrow?
Fill in your guesses before you run it.
fn main() { println!("i32 {} bytes", size_of::<i32>()); println!("&i32 {} bytes", size_of::<&i32>()); println!("String {} bytes", size_of::<String>()); println!("&String {} bytes", size_of::<&String>()); println!("&str {} bytes", size_of::<&str>()); println!("[i32; 1000] {} bytes", size_of::<[i32; 1000]>()); println!("&[i32; 1000] {} bytes", size_of::<&[i32; 1000]>()); }
| Type | Guess | Actual |
|---|---|---|
i32 | ||
&i32 | ||
String | ||
&String | ||
&str | ||
[i32; 1000] | ||
&[i32; 1000] |
a. Why is &[i32; 1000] so much smaller than [i32; 1000]?
b. Which reference is not 8 bytes, and why?
c. Change it: add a line for a type of your choice. bool? char? Vec<String>? &&i32? What did you try, and what did you get?
Experiment 5, if you finish early: an arrow to an arrow
fn main() { let x: i32 = 5; let r: &i32 = &x; let rr: &&i32 = &r; println!("x lives at {:p}", &x); println!("r holds {:p}", r); println!("r lives at {:p}", &r); println!("rr holds {:p}", rr); println!("{} {} {}", x, *r, **rr); }
a. Which addresses match? Draw x, r, and rr on the stack with their arrows.
b. Why does rr need two stars to get to the 5?
Solutions
Part 1
Problem 1.
Stack:
┌────────────────────┐
│ main() │
│ ├ x: i32 = 15 │◀──┐
│ ├ y: i32 = 20 │◀┐ │
│ ├ r1: &i32 ────────┼─┘ │
│ └ r2: &mut i32 ────┼───┘
└────────────────────┘
Stack only, nothing on the heap. x is 15, not 10: *r2 = 15 followed the arrow and wrote into x. r1 points at y and r2 at x, so both arrows end in the same frame they start in.
Problem 2.
Stack: Heap:
┌──────────────────────────┐
│ main() │
│ ├ numbers: Vec<i32> │◀──┐ ┌────┬────┬────┬────┐
│ │ ├ ptr ────────────────┼───┼───────▶│ 10 │ 20 │ 30 │ 40 │
│ │ ├ len: 4 │ │ └────┴────┴────┴────┘
│ │ └ cap: 4 │ │ ▲
│ ├ name: String │◀┐ │ │ ┌─────┬─────┬─────┬─────┬─────┐
│ │ ├ ptr ────────────────┼─┼─┼───────────────┼───▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │ ├ len: 5 │ │ │ │ └─────┴─────┴─────┴─────┴─────┘
│ │ └ cap: 5 │ │ │ │
│ ├ r1: &Vec<i32> ─────────┼─┼─┘ │
│ ├ r2: &i32 ──────────────┼─┼─────────────────┘
│ ├ r3: &String ───────────┼─┘
│ └ r4: &str │ Program binary:
│ ├ ptr ────────────────┼───────────▶┌───────┐
│ └ len: 3 │ │ "Bob" │
└──────────────────────────┘ └───────┘
Four arrows, ending in three different places. r1 and r3 end on the stack, at the handles: &numbers is a reference to the variable numbers, and that variable is the handle, not the numbers. r2 ends in the heap, at the 20, because &numbers[1] is a reference to one element. r4 is a &str, so it carries a len of its own and points into the program binary, where the literal "Bob" has been since compile time.
Part 2
Your addresses will differ from these. Which ones match, and which are close, should be the same on every machine.
Experiment 1.
score lives at 0x16f1ce6f4
points holds 0x16f1ce6f4
points lives at 0x16f1ce678
score 10, total 15
- a.
score lives atandpoints holdsmatch.pointsis&score, so what it holds isscore's address - b.
points lives atis close toscore, a few hundred bytes away at most, but not the same.pointsis a variable too, with its own spot on the stack, inwith_bonus's frame, which sits right on top ofmain's - c.
*points += 5;does not compile: "cannot assign to*points, which is behind a&reference". A&reference lets you read through the arrow but not write through it.
Experiment 2.
len 1 cap 4 data at 0x104955390
len 2 cap 4 data at 0x104955390
len 3 cap 4 data at 0x104955390
len 4 cap 4 data at 0x104955390
len 5 cap 8 data at 0x104955200
...
len 8 cap 8 data at 0x104955200
len 9 cap 16 data at 0x104955220
...
len 16 cap 16 data at 0x104955220
len 17 cap 32 data at 0x104955ea0
...
len 20 cap 32 data at 0x104955ea0
- a.
capchanges whenlencatches up to it: 4, 8, 16, 32. It doubles every time it fills - b. The address changes at the same moments. A bigger block means a new allocation somewhere else, and every element is copied over to it, then the old block is freed. (Now and then the allocator can grow a block in place, so the address may stay put once or twice)
- c. With
Vec::with_capacity(20),capis 20 from the first line and the address never changes. No regrowing and no copying, because the room was there from the start
Experiment 3.
- a.
error[E0597]: `x` does not live long enough - b.
xlives inside the braces and is dropped at the closing one.rwould still be pointing at wherexused to be, andprintln!would read it. The compiler refuses to make a dangling pointer, and the full message says wherexis dropped and where the borrow is used afterward - c. Moving the
println!inside the braces compiles and prints5. Nowris used whilexis still alive
Experiment 4.
| Type | Actual |
|---|---|
i32 | 4 |
&i32 | 8 |
String | 24 |
&String | 8 |
&str | 16 |
[i32; 1000] | 4000 |
&[i32; 1000] | 8 |
- a. A reference is an address, and an address is 8 bytes on a 64-bit machine no matter how big the thing it points at is.
&[i32; 1000]holds where to find the 4000 bytes, not the bytes - b.
&str, at 16. It is a fat pointer: an address plus a length, because the text it points at could be any length and nothing else records it.&Stringis 8, because theStringhandle carries its ownlen - c. Some to compare against:
boolis 1,charis 4,Vec<String>is 24,&&i32is 8. Every plain reference is 8
Experiment 5.
x lives at 0x16dd16634
r holds 0x16dd16634
r lives at 0x16dd16638
rr holds 0x16dd16638
5 5 5
- a.
x lives atmatchesr holds, andr lives atmatchesrr holds.r lives atis 4 bytes pastxhere:ris a variable on the stack too, right next tox
Stack:
┌──────────────────────┐
│ main() │
│ ├ x: i32 = 5 │◀───┐
│ ├ r: &i32 ───────────┼────┘
│ │ ▲ │
│ └ rr: &&i32 │
└──────────────────────┘
- b. Each
*follows one arrow.rrpoints atr, so*rrisr, which is itself an arrow. One more*follows that arrow to the 5
Activity 20: Let's Talk Glitches
Games from the 1990s were written in assembly language, with nobody checking their memory but the programmers. Today we look at what happens when a game follows a pointer somewhere it shouldn't.
In class
- Watch The MissingNo Glitch (about 6 minutes)
- On Gradescope, answer:
- Which kinds of bugs from today's lecture led to this behavior?
- How would Rust have prevented them?
- Just for fun: Mario creating a glitch level out of memory
Want more?
- Why MissingNo looks the way it does: integer overflow, signed and unsigned integers, and buffer overflows
- The Mew glitch
Activity 21: Acting out ownership
What everything is
- A person is a variable. Their name is taped on and never moves
- Red is a value. A number is a blue sheet in the variable's own hands: the stack
- A heap value is a blue sheet at the side of the room, held by someone with no name tag. The heap has addresses, not names
- A leash is a pointer. The variable holds the handle end. The clip end is on the heap sheet
- Whoever holds the leash owns the value. When the owner is done, they let go, and the sheet gets thrown out
Act 1: Copy vs Move
Cast: x, y, s1, s2, one heap holder, the allocator.
fn main() { let x = 5; let y = x; let s1 = String::from("hello"); let s2 = s1; println!("{} {}", x, y); // println!("{} {}", s1, s2); }
Act 2: Function calls and returning ownership
Cast: data, numbers, a second data, one heap holder, the allocator. Tape the rectangle for process.
fn main() { let data = vec![1, 2, 3]; let data = process(data); println!("{:?}", data); // Works! } fn process(mut numbers: Vec<i32>) -> Vec<i32> { numbers.push(4); numbers }
Act 3: Attack of the Clones
Cast: s1, s2, s3, s4, two heap holders, the allocator.
fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); println!("{} {}", s1, s2); let s3 = s1; let s4 = s2; println!("{} {}", s3, s4); }
Activity 22: The Box Office, and Debugging Ownership
Name(s):
Part 1: The Box Office
Cast: 11 people.
fn main() { let venue = String::from("Stage"); let guest_list = vec![ String::from("Alice"), String::from("Bob") ]; // Box in a Box! let vip_box = Box::new(Box::new(String::from("VIP"))); let show = prepare_show(guest_list, vip_box); println!("Show at {}", venue); println!("Final show: {:?}", show); } fn prepare_show(mut guests: Vec<String>, special: Box<Box<String>>) -> Box<Vec<String>> { guests.push(String::from("Charlie")); guests.push(**special); // Unbox twice! Box::new(guests) }
Part 2: three programs that won't compile
For each one:
- Read the compiler message.
- Describe briefly what went wrong, in terms of owners
- Try to come up with two different fixes. Which would you use, and why?
Error 1
fn main() { let data = vec![1, 2, 3]; process_data(data); println!("{:?}", data); } fn process_data(vec: Vec<i32>) { println!("Processing: {:?}", vec); }
Compiler says: borrow of moved value: data
What went wrong:
Fix 1:
Fix 2:
Which would you use, and why?
Error 2
fn main() { let message = String::from("Hello"); let a = message; let b = message; println!("{} {}", a, b); }
Compiler says: use of moved value: message
What went wrong:
Fix 1:
Fix 2:
Which would you use, and why?
Error 3
fn main() { let names = vec![String::from("Alice"), String::from("Bob")]; let first = names[0]; println!("{}", first); }
Compiler says: cannot move out of index of Vec<String>
What went wrong:
Fix 1:
Fix 2:
Which would you use, and why?
Bonus. This program compiles fine:
fn main() { let numbers = vec![10, 20, 30]; let first = numbers[0]; println!("{}", first); }
Same shape, no error. What's different?
Solutions
Error 1
data moved into process_data and was dropped at its closing brace.
Fix 1: have process_data return the vector, and rebind let data = process_data(data);.
Fix 2: process_data(data.clone()).
Error 2
message moved into a, so there's nothing left to move into b.
Fix 1: let a = message.clone(); and move the original into b
Fix 2: Clone both, or use &
Error 3
Moving the String out would leave a hole in the vector.
Fix 1: names[0].clone().
Fix 2: &names[0]
Bonus: same shape, no error
What's different?
i32 is Copy and String isn't.
Activity 23: Draw the slice
Name:
Both problems are done during lecture. Hand this in on your way out.
Stack on the left, heap on the right. Label everything!
Problem 1
#![allow(unused)] fn main() { let data = vec![5, 10, 15, 20, 25]; let slice = &data[1..4]; }
How many fields does data have on the stack? How many does slice?
Problem 2
fn analyze(numbers: &Vec<i32>, window: &[i32]) -> i32 { let first = window[0]; let sum_ref = &first; // DRAW HERE let total = first + numbers.len() as i32; total } fn main() { let data = vec![100, 200, 300, 400]; let slice = &data[1..3]; let result = analyze(&data, slice); }
sum_ref is a reference. Is anything it touches on the heap?
Solutions
Problem 1. data is a ptr/len/cap handle on the stack, heap buffer holding 5, 10, 15, 20, 25. slice is two words on the stack: a pointer to the element at index 1, and the length 3.
Stack: Heap:
┌───────────────────────┐
│ main() │
│ ├ data: Vec<i32> │ ┌────┬────┬────┬────┬────┐
│ │ ├ ptr ─────────────┼───────▶│ 5 │ 10 │ 15 │ 20 │ 25 │
│ │ ├ len: 5 │ └────┴────┴────┴────┴────┘
│ │ └ cap: 5 │ ▲
│ └ slice: &[i32] │ │ (at the 10, index 1)
│ ├ ptr ─────────────┼───────────────┘
│ └ len: 3 │
└───────────────────────┘
Problem 2. Two frames. main has data (handle, heap buffer 100, 200, 300, 400), slice (ptr to index 1, len 2), and result, which is ??? because analyze hasn't returned. analyze has numbers, an arrow back to main's handle; window, a copy of the two-word slice; first, an i32 holding 200 on analyze's frame; sum_ref, an arrow to first, which is on the stack; and total, ??? because that line hasn't run yet.
Stack: Heap:
┌─────────────────────────┐
│ analyze() │
│ ├ numbers: &Vec<i32> ───┼─────┐
│ ├ window: &[i32] │ │
│ │ ├ ptr ───────────────┼─────┼───────────┐
│ │ └ len: 2 │ │ │
│ ├ first: i32 = 200 │◀─┐ │ │
│ ├ sum_ref: &i32 ────────┼──┘ │ │
│ └ total: i32 = ??? │ │ │
├─────────────────────────┤ │ │
│ main() │ │ ▼ (window: at the 200, index 1)
│ ├ data: Vec<i32> │◀────┘ ┌─────┬─────┬─────┬─────┐
│ │ ├ ptr ───────────────┼───────▶│ 100 │ 200 │ 300 │ 400 │
│ │ ├ len: 4 │ └─────┴─────┴─────┴─────┘
│ │ └ cap: 4 │ ▲
│ ├ slice: &[i32] │ │ (slice: the same 200)
│ │ ├ ptr ───────────────┼─────────────────┘
│ │ └ len: 2 │
│ └ result: i32 = ??? │
└─────────────────────────┘
Activity 24: Be the Borrow Checker!
For each code snippet below:
- Circle each borrow
- Draw a bracket around each borrow's scope (from creation to last use)
- Label each borrow scope as
&(immutable) or&mut(mutable) - Mark any conflicts where borrows violate the rules
- Decide whether the code will compile or not (and if not, why not)
Borrow Checker Rules:
- Rule 1: You can have EITHER many immutable references OR one mutable reference (not both)
- Rule 2: References must be valid (can't outlive the data they point to)
Problem 1 - let's do it together
fn main() { let mut scores = vec![142, 167, 125]; let reader = &scores; println!("Bowling scores: {:?}", reader); let writer = &mut scores; writer.push(189); println!("After one more game: {:?}", writer); }
Problem 2 - let's do it together
fn main() { let outer; // declared here, set later { let inner = vec![1, 2, 3]; outer = &inner; println!("Inside: {:?}", outer); } println!("Outside: {:?}", outer); }
Problem 3
struct Player { name: String, score: u32, } fn main() { let p = Player { name: String::from("Alice"), score: 10 }; let whole = &p.name; let start = &p.name[..3]; println!("{}", whole); println!("{}", start); println!("{} {}", p.name, p.score); }
Problem 4
fn main() { let mut balance = 100; let view = &balance; println!("Before: {}", view); balance += 50; println!("After: {}, was {}", balance, view); }
Problem 5
fn main() { let mut values = vec![1, 2, 3]; let modifier1 = &mut values; modifier1.push(4); let modifier2 = &mut values; modifier2.push(5); println!("{:?} {:?}", modifier1, modifier2); }
Problem 6
fn main() { let mut data = vec![10, 20, 30]; let biggest = largest(&data); println!("Biggest: {:?}", biggest); add_bonus(&mut data, 5); println!("Data: {:?}", data); } fn largest(numbers: &Vec<i32>) -> Option<&i32> { numbers.iter().max() } fn add_bonus(numbers: &mut Vec<i32>, bonus: i32) { for num in numbers.iter_mut() { *num += bonus; } }
Problem 7
fn main() { let mut names = vec![String::from("Al"), String::from("Bo")]; let first = names.first(); names.push(String::from("Cy")); println!("First name: {:?}", first); }
Problem 8
fn main() { let mut numbers = vec![1, 2, 3, 4, 5]; for num in numbers.iter() { println!("{}", num); let num_ref = &mut numbers; num_ref.push(*num * 2); } }
Fun (and useful) fact - the same thing happens when you do numbers.push() without let ...
Problem 9
fn create_message() -> &String { let msg = String::from("Hello"); return &msg; } fn main() { let message = create_message(); println!("{}", message); }
Solutions
- Compiles.
readerends beforewriterstarts - No, rule 2.
innerdies at the closing brace,outeris used after - Compiles. Two readers of
p.name, then the owner reads - No, rule 1.
balance += 50writes whileviewis still used on the last line - No, rule 1. Two
&mutboth alive at the finalprintln! - Compiles.
largesthands a reference back, sobiggestkeepsdataborrowed until line 5; the writer comes after - No, rule 1.
firstisSome(&String)into the vector, so the whole vector is borrowed;pushneeds&mut - No, rule 1.
.iter()holds&numbersfor the whole loop - No, rule 2.
&msgoutlivesmsg. Same asget_namefrom lecture
Activity 25: Diagrams and Trade-offs
Name(s):
Part 1: Draw what crosses the frame
Draw the state at the marked line.
Problem 1
fn process(x: &mut i32, y: &i32) { *x += *y; // DRAW HERE } fn main() { let mut a = 10; let b = 5; process(&mut a, &b); }
Problem 2
fn append_data(list: &mut Vec<i32>, value: i32) { list.push(value); let last = &list[list.len() - 1]; // DRAW HERE } fn main() { let mut numbers = vec![10, 20]; append_data(&mut numbers, 30); }
Part 2: Three versions, all correct
Three people wrote the same function. All three compile and work correctly.
#![allow(unused)] fn main() { // Version A // `mut names` here may be unfamiliar, but it lets us make names mutable // and acts like we did `let mut names = ...` fn add_tag(mut names: Vec<String>) -> Vec<String> { names.push(String::from("new")); names } // called as: let names = add_tag(names); }
#![allow(unused)] fn main() { // Version B fn add_tag(names: &Vec<String>) -> Vec<String> { let mut out = names.clone(); out.push(String::from("new")); out } // called as: let names = add_tag(&names); }
#![allow(unused)] fn main() { // Version C fn add_tag(names: &mut Vec<String>) { names.push(String::from("new")); } // called as: add_tag(&mut names); }
1. Write one pro and one con for each. Think about what happens to the caller's vector afterward, and about how much work happens per call.
| Pro | Con | |
|---|---|---|
| A | ||
| B | ||
| C |
2. Rank them, best first, for a vector holding ten thousand names.
_______ , _______ , _______
3. Does your ranking change if the vector holds three names? Why or why not?
4. Your caller needs the original vector, unchanged, after the call. Which versions still work?
Only B. A took the original away and gave you back a revised one. C changed it in place. B is the expensive one and the only one that meets this requirement.
5. Imagine you are conducting a code review for someone who wrote the version you ranked last. Write a question or observation you could imagine bringing up to the person who wrote it.
Good review comments ask about design choices more than syntax:
- "This clones the whole vector on every call, was that on purpose?"
- "The caller has to rebind the result here, is that what you wanted?"
- "This changes the caller's vector, is that obvious enough at the call site?"
Each of those can be answered with "yes, because..." - what might look wrong to you at first could have a real reason behind it!
Solutions
Part 1
Problem 1
Stack: Heap:
┌─────────────────────────┐
│ process() │ (nothing)
│ ├ x: &mut i32 ──────────┼──┐
│ └ y: &i32 ──────────────┼──┼──┐
├─────────────────────────┤ │ │
│ main() │ │ │
│ ├ a: i32 = 15 (was 10) │◀─┘ │
│ └ b: i32 = 5 │◀────┘
└─────────────────────────┘
Problem 2
Stack: Heap:
┌───────────────────────────┐
│ append_data() │
│ ├ list: &mut Vec<i32> ────┼──┐
│ ├ value: i32 = 30 │ │
│ └ last: &i32 ─────────────┼──┼────────────────────────────────────┐
├───────────────────────────┤ │ │
│ main() │ │ │
│ └ numbers: Vec<i32> │◀─┘ ┌──────┬──────┬──────┬──────┐ │
│ ├ ptr ─────────────────┼──────▶│ 10 │ 20 │ 30 │ │ │
│ ├ len: 3 (was 2) │ └──────┴──────┴──────┴──────┘ │
│ └ cap: 4 (was 2) │ ▲ │
└───────────────────────────┘ (index 2) └─────────────┘
Part 2
All three compile, and all three are defensible.
- A takes the vector and hands it back. Works, but the caller has to rebind:
let names = add_tag(names);. Odd for a function whose whole job is "push one thing" - B is the only one that leaves the caller's vector alone. It's also the only one that copies every
String, so on ten thousand names it's the expensive one - C is what most Rust programmers write, and it's what
Vec::pushitself looks like. The cost: the caller's vector changes, and the&mutat the call site is the only warning
At ten thousand names: C, then A, then B. A moves a handle, B copies ten thousand strings.
At three names, the clone costs almost nothing, so rank on clarity. Any order you can defend is fine.
Activity 26: Find the Bug with Tests
Problem 1 we'll do together during lecture. Problems 2 and 3 are at the end, on a laptop. You can keep this sheet, you'll just answer questions on Gradescope today.
Blackjack scoring, in case you've never played
Number cards are worth their number. Face cards (J, Q, K) are worth 10. An ace is worth 11, unless that would put the hand over 21, in which case it's worth 1. A hand over 21 is a bust. Exactly two cards worth 21 together is a blackjack.
Problem 1: Plan the tests (in lecture)
Four functions. You'll get the code later. For now you have the signatures and what each one promises, which is all a test needs.
/// The value of one card. Panics if `card` is not a card.
pub fn card_value(card: &str) -> u32
/// The value of a whole hand. An ace counts as 1 instead of 11 when it has to.
pub fn hand_value(hand: &[&str]) -> u32
/// True when the hand is worth more than 21.
pub fn is_bust(hand: &[&str]) -> bool
/// True for a blackjack: exactly two cards worth 21 together.
pub fn is_blackjack(hand: &[&str]) -> bool
Cards are strings: "A", "K", "Q", "J", "10", "9", down to "2". A hand is a slice of them, so a call looks like hand_value(&["A", "K"]).
For each of the last three functions, plan two tests: one ordinary hand, and one hand at an edge. Ask what could go wrong. An ace that has to count as 1? A total of exactly 21? Three cards that add up to 21? Write the hand and what the function should return. The last column waits for Problem 2.
| Function | Which | Hand | Expected | Pass? |
|---|---|---|---|---|
hand_value | ordinary | |||
hand_value | edge | |||
is_bust | ordinary | |||
is_bust | edge | |||
is_blackjack | ordinary | |||
is_blackjack | edge | |||
card_value | bonus: not a card | panics |
Problem 2: Write them and run them
- Open the link on the screen. It isn't on the website.
- The whole program is one file. At the bottom is a
testsmodule withuse super::*and one test already in it. Yours go under it. - Type your six tests from the sheet. Give each a name that says what it checks, so a failure reads like a sentence.
- Click Test. The playground sees
#[test]and runscargo testinstead ofmain. - Fill in the Pass column on your sheet.
#[test]
fn king_and_five_is_fifteen() {
assert_eq!(hand_value(&["K", "5"]), 15);
}
Problem 3: Find the bug
At least one test should have failed.
Which function is wrong, and why? If every test passed, your edges weren't edgy enough. Ask your neighbor for ideas if they got tests to fail.
Hand in
On Gradescope, before the end of class:
- One test you wrote for an ordinary hand.
- One test you wrote for an edge case.
- Which function(s) had a bug?
Solutions
- Bug 1:
hand_valuechanges an ace to 1 only if the hand is already busting when the ace is dealt.["A", "K", "5"]= 26, should be 16.["K", "5", "A"]= 16 is correct, so order matters - Bug 2:
is_blackjacknever checks the card count.["7", "7", "7"]is 21 and reports blackjack is_bustis correctcard_value("Joker")panics withnot a card, for#[should_panic(expected = "not a card")]- Empty hand = 0, no panic
- Fix 1: count aces in the loop, then
while total > 21 && aces > 0 { total -= 10; aces -= 1; } - Fix 2:
hand.len() == 2 && hand_value(hand) == 21
The fixed file with the added tests:
// Blackjack scoring.
//
// Number cards are worth their number and face cards are worth 10.
// An ace is worth 11, unless that would push the hand over 21, in which
// case it is worth 1. A hand is bust when it is over 21. A blackjack is
// a hand of exactly two cards worth 21.
//
// Cards are written as strings: "A", "K", "Q", "J", "10", "9", ... "2".
//
// Fixed version: both bugs repaired.
/// The value of one card. Panics if `card` is not a card.
pub fn card_value(card: &str) -> u32 {
match card {
"A" => 11,
"K" | "Q" | "J" | "10" => 10,
"9" => 9,
"8" => 8,
"7" => 7,
"6" => 6,
"5" => 5,
"4" => 4,
"3" => 3,
"2" => 2,
_ => panic!("not a card: {}", card),
}
}
/// The value of a whole hand. An ace counts as 1 instead of 11 when it has to.
pub fn hand_value(hand: &[&str]) -> u32 {
let mut total = 0;
let mut aces = 0;
for card in hand {
total += card_value(card);
if *card == "A" {
aces += 1;
}
}
while total > 21 && aces > 0 {
total -= 10;
aces -= 1;
}
total
}
/// True when the hand is worth more than 21.
pub fn is_bust(hand: &[&str]) -> bool {
hand_value(hand) > 21
}
/// True for a blackjack: exactly two cards worth 21 together.
pub fn is_blackjack(hand: &[&str]) -> bool {
hand.len() == 2 && hand_value(hand) == 21
}
// The six planned tests plus the two bonus ones. Paste over the `tests`
// module in src/lib.rs to see which fail against the planted bugs, or
// into solution/lib.rs to see them all pass.
#[cfg(test)]
mod tests {
use super::*;
// hand_value
#[test]
fn king_and_five_is_fifteen() {
assert_eq!(hand_value(&["K", "5"]), 15);
}
#[test]
fn ace_counts_as_one_when_eleven_would_bust() {
assert_eq!(hand_value(&["A", "K", "5"]), 16, "the ace should drop to 1");
}
// is_bust
#[test]
fn twenty_five_is_bust() {
assert!(is_bust(&["K", "9", "6"]));
}
#[test]
fn exactly_twenty_one_is_not_bust() {
assert!(!is_bust(&["K", "9", "2"]));
}
// is_blackjack
#[test]
fn ace_and_king_is_blackjack() {
assert!(is_blackjack(&["A", "K"]));
}
#[test]
fn three_sevens_is_twenty_one_but_not_blackjack() {
assert!(!is_blackjack(&["7", "7", "7"]));
}
// bonus
#[test]
fn empty_hand_is_worth_zero() {
assert_eq!(hand_value(&[]), 0);
}
#[test]
#[should_panic(expected = "not a card")]
fn joker_is_not_a_card() {
card_value("Joker");
}
}
Activity 27: Confidence check, and passing sheets
Name:
This is not a quiz. You don't answer anything. Just read each line, mark how you feel about it, take a picture for Gradescope, and keep the paper for studying.
Mark one box per row:
- Got it. I could do this right now, on paper, with no help
- Shaky. I would get there, but slowly, or I would second-guess it.
- Study it. I need to go back to this before Friday.
Everything here is from Lectures 17 through 26.
Part 1: Memory, pointers, ownership
| Could you do this? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 1.1 | Say what a stack frame is, when it appears, and when it is thrown away | |||
| 1.2 | Say what a { } block inside a function does to a variable declared inside it | |||
| 1.3 | Say why the stack is fast, and what the heap can do that the stack can't | |||
| 1.4 | Say what a String on the stack is made of, and where its letters are | |||
| 1.5 | Say what a reference has that a raw pointer doesn't, and why only one of them needs unsafe | |||
| 1.6 | Say what unsafe is a promise about | |||
| 1.7 | List the seven memory bugs, and say which ones safe Rust turns into a compile error | |||
| 1.8 | Say the rule for which types copy and which types move, and where your own struct falls | |||
| 1.9 | Say what happens to the heap when a String moves, and when it is cloned | |||
| 1.10 | List the four steps a full Vec takes on a push | |||
| 1.11 | Say what Box::new(7) puts where |
Part 2: Strings, borrowing, tests
| Could you do this? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 2.1 | Tell String, &String, and &str apart, and say where each one's arrow ends | |||
| 2.2 | Say why s.len() and s.chars().count() can differ, and why s[0] is refused | |||
| 2.3 | Say what a byte-range slice does when it ends in the middle of a character | |||
| 2.4 | State the two borrowing rules, and say which C bug each one prevents | |||
| 2.5 | Say where a borrow ends, and why the owner's own name counts as a writer | |||
| 2.6 | Say what each of &T, &mut T, and T as a parameter costs the caller | |||
| 2.7 | Say what .iter_mut() hands you that .iter() doesn't, and what you do with it in the loop | |||
| 2.8 | Read fn f<'a>(x: &'a str) -> &'a str out loud and say what the 'a promises | |||
| 2.9 | Say what 'static means and which values have it | |||
| 2.10 | Write a test: the attribute, the function, an assert with a message | |||
| 2.11 | Tell a happy-path test from an edge-case test, and name three edges worth testing |
Part 3: Read the code
Don't answer these fully. Decide whether you could.
3.1 What does this print?
#![allow(unused)] fn main() { let a = String::from("go"); let mut b = a.clone(); b.push_str("!"); println!("{} {}", a, b); }
3.2 Does this compile? If so, what does it print?
#![allow(unused)] fn main() { let s = String::from("hi"); let a = &s; let b = &s; println!("{} {} {}", a, b, s.len()); }
3.3 Could you draw the stack and the heap after these three lines, with a type on every variable?
#![allow(unused)] fn main() { let v = vec![5, 6]; let b = Box::new(9); let r = &v; }
3.4 Does this compile? If not, which rule is broken, and on which line?
#![allow(unused)] fn main() { let mut x = 5; let a = &mut x; let b = &mut x; *a += 1; *b += 1; }
| Got it | Shaky | Study it | |
|---|---|---|---|
| 3.1 | |||
| 3.2 | |||
| 3.3 | |||
| 3.4 |
Part 4: Write it from nothing
On paper without notes. Could you do it?
| Could you write this? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 4.1 | A function that takes a &[i32] and gives back the largest number as Some(n), or None for an empty slice | |||
| 4.2 | A function that takes a &str and gives back a String that is three copies of the &str in a row | |||
| 4.3 | A function that takes a &mut Vec<i32> and doubles every number in place | |||
| 4.4 | Two tests for 4.1, one ordinary and one edge, each with a message |
Part 5: Say it out loud
| Could you explain this to someone? | Got it | Shaky | Study it | |
|---|---|---|---|---|
| 5.1 | Why a push can break a reference into the vector | |||
| 5.2 | What malloc hands you, and why you write before you read | |||
| 5.3 | For a memory mistake, whether safe Rust gives a compile error, a panic, or makes it impossible to write | |||
| 5.4 | Why .clone() costs more than & | |||
| 5.5 | Why a function that returns a reference to its own local variable can't compile |
Activity 29: Traits
We did Problems 1 to 3 together in lecture, on the handout. Problem 4 was the laptop part, handed in on Gradescope.
Problem 1: implement a trait (in lecture)
Describe and print_card are the ones from the slides:
trait Describe {
fn describe(&self) -> String;
}
fn print_card(item: &impl Describe) {
println!("{}", item.describe());
}
Write the impl block so that this program prints a 20-sided die.
struct Die { sides: u32 }
// your impl here
fn main() {
let d20 = Die { sides: 20 };
print_card(&d20);
}
Answer.
impl Describe for Die {
fn describe(&self) -> String {
format!("a {}-sided die", self.sides)
}
}
Problem 2: default methods (in lecture)
trait Scorer {
fn points(&self) -> u32;
fn label(&self) -> String {
format!("{} points", self.points())
}
}
struct Touchdown;
struct FieldGoal;
impl Scorer for Touchdown {
fn points(&self) -> u32 { 6 }
}
impl Scorer for FieldGoal {
fn points(&self) -> u32 { 3 }
fn label(&self) -> String { String::from("three, kicked") }
}
fn main() {
println!("{}", Touchdown.label());
println!("{}", FieldGoal.label());
}
- What are the two lines this prints?
- Add a
Safety, worth 2 points, that uses the default label. Write the struct and itsimpl.
Answer. It prints 6 points, then three, kicked. Touchdown never wrote label, so it gets the default from the trait.
struct Safety;
impl Scorer for Safety {
fn points(&self) -> u32 { 2 }
}
Problem 3: implement Ord (in lecture)
sort needs Ord, and Ord is one method:
trait Ord {
fn cmp(&self, other: &Self) -> Ordering;
}
enum Ordering { Less, Equal, Greater }
Write impl Ord for Striker so that strikers.sort() puts the fewest goals first. u32 already knows how to cmp, so 7.cmp(&12) is Ordering::Less.
Ord needs Eq too, which is like PartialEq but also needs every value to equal itself. That's the extra word in the derive line.
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq)]
struct Striker { name: String, goals: u32 }
// your impl Ord here
// Rust also wants PartialOrd. It just asks Ord:
impl PartialOrd for Striker {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
If you have time: what one change puts the most goals first?
Answer.
impl Ord for Striker {
fn cmp(&self, other: &Self) -> Ordering {
self.goals.cmp(&other.goals)
}
}
The body hands the job to u32's own cmp. Writing it out with if self.goals < other.goals { Ordering::Less } ... works too. For most goals first, swap the two sides: other.goals.cmp(&self.goals).
Problem 4: shapes (on a laptop)
The starting file is at tinyurl.com/210shape, with these steps as comments at the top. It compiles as is, and panics at the first todo!().
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
fn describe(&self) -> String {
format!("{} with area {:.1}", self.name(), self.area())
}
}
struct Rectangle { width: f64, height: f64 }
struct Circle { radius: f64 }
impl Shape for Rectangle {
fn area(&self) -> f64 { todo!() }
fn name(&self) -> String { todo!() }
}
impl Shape for Circle {
fn area(&self) -> f64 { todo!() }
fn name(&self) -> String { todo!() }
}
fn main() {
let rect = Rectangle { width: 5.0, height: 3.0 };
let circle = Circle { radius: 2.0 };
println!("{}", rect.describe());
println!("{}", circle.describe());
}
Step 1. Fill in the four todo!()s. A rectangle's area is width times height; a circle's is PI times the radius squared. Run it. You should see rectangle with area 15.0 and circle with area 12.6.
Neither impl mentions describe. Where did it come from?
Step 2. Replace main with one that puts both shapes, plus a Rectangle { width: 2.0, height: 2.0 }, into a single vector, then loops over it printing describe() for each:
let shapes: Vec<Box<dyn Shape>> = vec![
// the three shapes, each inside Box::new(...)
];
for shape in &shapes {
// print each description
}
Try Vec<Shape> first, so you've seen the error. Then fix it.
Step 3. Add a third kind of shape: struct Triangle { base: f64, height: f64 }, with area half the base times the height. Write its impl Shape and add a Triangle { base: 6.0, height: 4.0 } to the vector. What did you have to change in the loop?
On Gradescope: your impl Shape for Circle, what your program prints, and one sentence on why the vector can't be Vec<Shape>.
Answer. After all three steps:
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String;
fn describe(&self) -> String {
format!("{} with area {:.1}", self.name(), self.area())
}
}
struct Rectangle { width: f64, height: f64 }
struct Circle { radius: f64 }
struct Triangle { base: f64, height: f64 }
impl Shape for Rectangle {
fn area(&self) -> f64 { self.width * self.height }
fn name(&self) -> String { String::from("rectangle") }
}
impl Shape for Circle {
fn area(&self) -> f64 { PI * self.radius * self.radius }
fn name(&self) -> String { String::from("circle") }
}
impl Shape for Triangle {
fn area(&self) -> f64 { 0.5 * self.base * self.height }
fn name(&self) -> String { String::from("triangle") }
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Rectangle { width: 5.0, height: 3.0 }),
Box::new(Circle { radius: 2.0 }),
Box::new(Rectangle { width: 2.0, height: 2.0 }),
Box::new(Triangle { base: 6.0, height: 4.0 }),
];
for shape in &shapes {
println!("{}", shape.describe());
}
}
It prints rectangle with area 15.0, circle with area 12.6, rectangle with area 4.0, triangle with area 12.0. Neither impl wrote describe, they used the trait's default method. Adding the triangle changed nothing in the loop, because the loop only asks for a Shape.
The vector can't be a Vec<Shape> because Shape is a trait, a promise about types, and a Vec needs one type with one size. A Box<dyn Shape> is a pointer, which has a size.
Challenge: Display by hand
Implement Display for Rectangle so that println!("{}", rect) prints 5 x 3. You'll need use std::fmt; and an impl fmt::Display for Rectangle with one fmt method, like the Suit example from lecture.
Answer.
use std::fmt;
impl fmt::Display for Rectangle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} x {}", self.width, self.height)
}
}
Activity 30: Generics
Name:
Problem 1 we'll do together in lecture. Problems 2 to 5 run right here on the website: edit the code in the box, press the play button in its corner, read the error, and fix it. Don't refresh the page, or your edits will disappear.
Write your answers on the sheet and hand it in on your way out.
Problem 1: keep both (in lecture)
Our max takes ownership of both arguments. After max(a, b) with two strings, a and b are moved and we can't use them again.
fn max<T: PartialOrd>(x: T, y: T) -> T {
if x > y { x } else { y }
}
Rewrite max so the caller keeps a and b, and still gets back a T of its own. Hint: T: PartialOrd + Debug asks for two traits at once.
Problems 2 to 5 are on the laptop. For 2, 3, and 4, write the first line of the function once it compiled.
Problem 2. print_twice
Problem 3. is_greater
Problem 4. compare_and_print
Problem 5. Once it runs, add println!("{:?}", pair); as the last line of main. Does it compile? What does the compiler say, in a few words?
Problem 2: print it twice (together)
Add the bound that makes this compile. If you write just Debug, the compiler will ask for one more line.
fn print_twice<T>(value: T) { println!("{:?}", value); println!("{:?}", value); } fn main() { print_twice(42); print_twice("hello"); }
Problem 3: comparing
Same idea. Read the help: line before you fix it. It's most of the answer.
fn is_greater<T>(a: T, b: T) -> bool { a > b } fn main() { println!("{}", is_greater(5, 3)); println!("{}", is_greater(2.5, 7.8)); println!("{}", is_greater("pear", "apple")); }
Problem 4: two bounds at once
This function compares and prints, so one bound isn't enough.
fn compare_and_print<T>(a: T, b: T) { if a > b { println!("{:?} is greater", a); } else if a == b { println!("They're equal!"); } else { println!("{:?} is greater", b); } } fn main() { compare_and_print(5, 3); compare_and_print(2.5, 7.8); compare_and_print('q', 'q'); }
Problem 5: a generic pair
A Pair<T> holds two values of the same type. Fill in both todo!() lines.
#[derive(Debug)] struct Pair<T> { first: T, second: T, } impl<T> Pair<T> { // 1. Build a Pair. fn new(first: T, second: T) -> Pair<T> { todo!() } // 2. Return a new Pair with the two values traded. fn swap(self) -> Pair<T> { todo!() } } fn main() { let pair = Pair::new(5, 10); println!("Original: {:?}", pair); // Pair { first: 5, second: 10 } let swapped = pair.swap(); println!("Swapped: {:?}", swapped); // Pair { first: 10, second: 5 } let words = Pair::new("left", "right"); println!("{:?}", words.swap()); // Pair { first: "right", second: "left" } }
Once it runs, add println!("{:?}", pair); as the last line of main. Does it compile? Write what the compiler says on your sheet.
If you finish early
Two different types. Give Pair a second type parameter, so the two values can be different types. Look at what swap returns.
#[derive(Debug)] struct Pair<T, U> { first: T, second: U, } impl<T, U> Pair<T, U> { fn new(first: T, second: U) -> Pair<T, U> { todo!() } fn swap(self) -> Pair<U, T> { todo!() } } fn main() { let mixed = Pair::new(42, "hello"); // Pair<i32, &str> let swapped = mixed.swap(); // what type is this? println!("{:?}", swapped); }
Your own Option. Write a generic enum Maybe<T> with two variants, Just(T) and Nothing, and give it two methods. main is written for you. It won't compile until Maybe exists.
// 1. Write the enum: Maybe<T>, with variants Just(T) and Nothing. // 2. Write an impl block for it with two methods: // is_just(&self) -> bool // unwrap_or(self, fallback: T) -> T fn main() { let found = Maybe::Just(3); let missing: Maybe<i32> = Maybe::Nothing; println!("{}", found.is_just()); // true println!("{}", missing.is_just()); // false println!("{}", found.unwrap_or(0)); // 3 println!("{}", missing.unwrap_or(0)); // 0 }
Solutions
- P1:
fn max<T: PartialOrd + Clone>(x: &T, y: &T) -> T { if x > y { x.clone() } else { y.clone() } }, called asmax(&a, &b). Three changes:&T,.clone(),+ Clone. - P2:
fn print_twice<T: Debug>(value: T)plususe std::fmt::Debug;at the top.T: std::fmt::Debugwith nousealso works - P3:
fn is_greater<T: PartialOrd>(a: T, b: T) -> bool - P4:
fn compare_and_print<T: PartialOrd + Debug>(a: T, b: T)plus theuse. - P5: No.
swaptakesself, sopairwas moved. "borrow of moved value:pair"
Problem 5:
#![allow(unused)] fn main() { impl<T> Pair<T> { fn new(first: T, second: T) -> Pair<T> { Pair { first, second } } fn swap(self) -> Pair<T> { Pair { first: self.second, second: self.first } } } }
Finish-early:
#![allow(unused)] fn main() { // Pair<T, U> fn new(first: T, second: U) -> Pair<T, U> { Pair { first, second } } fn swap(self) -> Pair<U, T> { Pair { first: self.second, second: self.first } } // swapped is Pair<&str, i32> // Maybe<T> enum Maybe<T> { Just(T), Nothing, } impl<T> Maybe<T> { fn is_just(&self) -> bool { match self { Maybe::Just(_) => true, Maybe::Nothing => false, } } fn unwrap_or(self, fallback: T) -> T { match self { Maybe::Just(value) => value, Maybe::Nothing => fallback, } } } }
Activity 31: The room is a hash table
Name:
Today the room is the hash table. There are eight buckets on the walls, numbered 0 to 7. Your key is your first name. Each round puts a hash function on the screen; work out your bucket and go stand in it.
Letter values, for every round:
| A | B | C | D | E | F | G | H | I | J | K | L | M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
Round 1: first letter (in lecture)
hash(name) = value of the first letter. Bucket = hash % 8.
| Bucket | First letter |
|---|---|
| 0 | H P X |
| 1 | A I Q Y |
| 2 | B J R Z |
| 3 | C K S |
| 4 | D L T |
| 5 | E M U |
| 6 | F N V |
| 7 | G O W |
My bucket: ______ Longest pile: ______ Empty buckets: ______
Round 2: length
hash(name) = number of letters. Bucket = hash % 8. (Eight letters is bucket 0, nine is bucket 1.)
My bucket: ______ Longest pile: ______ Empty buckets: ______
Two names, Alice and Alicia, differ by one letter. Where do they land? Which property from the hash function slide does this function lack?
Answer. Alice is in bucket 5 and Alicia in bucket 6, but so is every other five- and six-letter name. The missing property is avalanche: a small change should scramble the whole output, and here it moves the key one bucket over. Uniform fails too, since most names are four to seven letters long so buckets 1 to 3 are empty.
Round 3: design a better one
With the people from your Round 2 bucket, design a hash function for first names that:
- anyone can compute in their head in ten seconds
- uses more of the name than one letter
- spreads this room more evenly than Rounds 1 and 2
Our function:
My bucket under it: ______ If we ran it, longest pile: ______
Answer. Anything that mixes two or more letters helps: first letter plus last letter, the sum of every letter, first letter plus length. On this term's roster those get the longest pile down from 8-12 to 5-7, vs an ideal of about 4. T
Round 4: two questions
a. Pick a brand-new name that would land in the fullest bucket under your group's function. How long did that take you? Which property is missing, and how does Rust's default hasher defend against it?
Answer. Seconds. Every function in this room is easy to run backwards: pick the bucket, pick letters that add up to it. That's an adversary choosing keys to collide. Rust's default hasher, SipHash, mixes every byte of the key with a random secret chosen when the program starts, so nobody outside the program can predict which keys collide.
b. Would your function still be flat for the other section's names? What does that say about what a hash function has to be good at?
Answer. No way to know. You designed it against the names in this room, like a library that knows its collection. A hash table doesn't know its keys ahead of time, so the function has to spread out keys it has never seen. That's what uniform means.
Activity 32: Heaps on paper
Name:
Problem 1: read the Vec (in lecture)
A BinaryHeap<i32> prints as:
[50, 40, 35, 25, 30, 30, 15]
Parent of i is (i - 1) / 2. Children of i are 2i + 1 and 2i + 2.
- What are the children of the element at index 1 (the 40)?
- What is the parent of the element at index 4 (the 30)?
- Is this a valid max-heap? Which pairs did you check?
- Draw the tree.
Answer.
- Indices
2 * 1 + 1 = 3and2 * 1 + 2 = 4: 25 and 30 - Index
(4 - 1) / 2 = 1: 40 - Yes. 50 >= 40, 35. 40 >= 25, 30. 35 >= 30, 15
- 50 on top; 40 and 35 under it; 25 and 30 under 40; 30 and 15 under 35
Problem 2: which of these are max-heaps?
Tree A: Tree B: Tree C:
90 70 80
/ \ / \ / \
75 60 65 72 70 60
/ \ / / \ / \
40 55 58 30 40 50 55
- Which trees are valid max-heaps?
- For each one that isn't, say what's wrong: the heap property, or the shape?
- Write Tree A as a
Vec.
Answer.
- Tree A only
- Tree B breaks the heap property: 72 is a child of 70. Tree C has the right values in the right order but isn't complete: the last row has a gap under 60, so the rows can't be laid end to end in a
Vec [90, 75, 60, 40, 55, 58]
Problem 3: trace a push and a pop
Start from this max-heap. After every swap, draw the tree and write the Vec under it.
60
/ \
45 50
/ \ /
20 30 40
[60, 45, 50, 20, 30, 40]
a. Push 55. How many comparisons did it take, and how many swaps?
Answer. 55 goes in at index 6, the right child of 50. 55 > 50, swap. 55 < 60, stop.
60
/ \
45 55
/ \ / \
20 30 40 50
[60, 45, 55, 20, 30, 40, 50]
b. Now pop. What comes out? Draw the heap after every swap.
Answer. 60 comes out. The last value, 50, moves to the root. Its children are 45 and 55, and 55 is the larger, so swap with 55. Now 50's only child is 40, which is smaller, so stop.
55
/ \
45 50
/ \ /
20 30 40
[55, 45, 50, 20, 30, 40]
Swapping with 45 instead would have put 55 under 45, which breaks the heap property.
Problem 4: read one, write one
a. What does this print? Each print! goes on the same line.
use std::collections::BinaryHeap;
fn main() {
let mut heap = BinaryHeap::new();
for cost in [12, 4, 9, 4, 20] {
heap.push(cost);
}
println!("{:?}", heap.peek()); // line A
heap.pop();
heap.push(25);
for _ in 0..5 {
print!("{} ", heap.pop().unwrap()); // line B
}
}
Line A: ________________________ Line B: ________________________
Answer. Line A prints Some(20). peek returns an Option, since the heap might be empty, and the biggest is on top.
Line B prints 25 12 9 4 4. The pop took out the 20, the push added a 25, and the loop drains biggest-first. Duplicates are fine in a heap.
b. Write best_two, which takes a Vec<i32> of scores and returns the two highest as a tuple, highest first. Use BinaryHeap::from and pop. unwrap is fine here, since the test has plenty of scores.
use std::collections::BinaryHeap;
fn best_two(scores: Vec<i32>) -> (i32, i32) {
}
fn main() {
println!("{:?}", best_two(vec![31, 7, 44, 12, 58])); // (58, 44)
}
What's the Big-O of best_two, for n scores? How does that compare to sorting the Vec and reading the last two?
Answer.
fn best_two(scores: Vec<i32>) -> (i32, i32) {
let mut heap = BinaryHeap::from(scores);
let first = heap.pop().unwrap();
let second = heap.pop().unwrap();
(first, second)
}
BinaryHeap::from is O(n), and each pop is O(log n), so O(n + 2 log n) = O(n). Sorting first is O(n log n), and it orders every score when we only wanted two.
Problem 5: which structure?
For each one, pick Vec, sorted Vec, HashSet, or BinaryHeap, and say in a few words why.
- A game server has thousands of scheduled events, each with a time. Every tick, run whichever is soonest. New events get scheduled constantly.
- Dealing cards: before handing one out, check whether it's already been dealt this hand.
- The moves of a chess game, in the order they were played, for replay.
- A leaderboard printed once, in full, top to bottom, when the tournament is over.
Answer.
BinaryHeap, set up so the soonest time counts as biggest (the appendix onReverseshows how). Pushes and pops keep coming, and each one is O(log n). A sortedVecwould cost O(n) per new eventHashSet. The question is "is this in here?", and that's O(1)Vec. Order of arrival, read back in order. Nothing to search for- Sort a
Veconce, O(n log n).
Activity 33: The printer queue
Name:
Problem 1: trace a ring (in lecture)
A VecDeque<i32> with capacity 4, starting empty:
push_back(7), push_back(3), push_back(9), push_back(10)
pop_front(), pop_front()
push_back(4)
push_front(8)
- Draw the block after every line, with
headandlennext to it. Elementilives at slot(head + i) % 4. - What does
println!("{:?}", line)print at the end? - Which slot holds the front of the queue? Which slot holds the back?
Answer.
push_back x4: [ 7 | 3 | 9 | 10 ] head 0 len 4
pop_front x2: [ | | 9 | 10 ] head 2 len 2
push_back(4): [ 4 | | 9 | 10 ] head 2 len 3
push_front(8): [ 4 | 8 | 9 | 10 ] head 1 len 4
[8, 9, 10, 4]. Printing starts atheadand walks around the ring- The front is slot 1 (the 8), because
push_frontsteppedheadback from 2 to 1. The back is slot 0 (the 4):(head + len - 1) % 4 = (1 + 4 - 1) % 4 = 0, so it wrapped
Problem 2: the printer queue
A printer takes jobs in the order they arrive, except that an urgent job cuts to the front. Build it on a VecDeque.
The cell below runs right here on the website: edit the code in the box, press the play button in its corner, read the output. Don't refresh the page, or your edits will disappear.
We'll write new, add_job, and print_next together. Then add_urgent_job, total_pages, and print_all are yours. You'll fill in everywhere that's marked todo!().
use std::collections::VecDeque; #[derive(Debug)] struct PrintJob { id: u32, pages: u32, } #[derive(Debug)] struct PrinterQueue { jobs: VecDeque<PrintJob>, } impl PrinterQueue { fn new() -> PrinterQueue { // An empty queue todo!() } fn add_job(&mut self, id: u32, pages: u32) { // A normal job joins at the back todo!() } fn add_urgent_job(&mut self, id: u32, pages: u32) { // An urgent job cuts to the front todo!() } fn total_pages(&self) -> u32 { // Add up the pages of every job waiting. A for loop over &self.jobs works todo!() } fn print_next(&mut self) { // Take the next job and print "Printing job [id]: [pages] pages" // If there's nothing waiting, print "Nothing to print" todo!() } fn print_all(&mut self) { // Print every job that's waiting, in order todo!() } } fn main() { let mut printer = PrinterQueue::new(); printer.add_job(1, 5); printer.add_job(2, 10); printer.add_job(3, 3); println!("Pages waiting: {}", printer.total_pages()); printer.print_next(); printer.add_urgent_job(99, 2); printer.print_all(); printer.print_next(); }
If it runs with time to spare, try adding these to the same cell and call them from main:
fn queue_size(&self) -> usize: how many jobs are waitingfn peek_next(&self) -> Option<&PrintJob>: the next job, without taking itfn cancel_job(&mut self, id: u32) -> bool: remove one job by itsid, and say whether it was there
What your program printed when every todo!() was filled in:
Question 1. Why is VecDeque the right structure here, and what would go wrong with a Vec?
Question 2. total_pages walks through every job, so it's O(n). How would you make it O(1)?
Solutions
Complete code:
#![allow(unused)] fn main() { impl PrinterQueue { fn new() -> PrinterQueue { PrinterQueue { jobs: VecDeque::new() } } fn add_job(&mut self, id: u32, pages: u32) { self.jobs.push_back(PrintJob { id, pages }); } fn add_urgent_job(&mut self, id: u32, pages: u32) { self.jobs.push_front(PrintJob { id, pages }); } fn total_pages(&self) -> u32 { let mut total = 0; for job in &self.jobs { total += job.pages; } total } fn print_next(&mut self) { match self.jobs.pop_front() { Some(job) => println!("Printing job {}: {} pages", job.id, job.pages), None => println!("Nothing to print"), } } fn print_all(&mut self) { while !self.jobs.is_empty() { self.print_next(); } } } }
Extensions: queue_size is self.jobs.len(). peek_next is self.jobs.front(). cancel_job is a for i in 0..self.jobs.len() loop that checks self.jobs[i].id, calls self.jobs.remove(i), and returns true; false after the loop.
Follow-up questions
What your program printed:
Expected output.
Pages waiting: 18
Printing job 1: 5 pages
Printing job 99: 2 pages
Printing job 2: 10 pages
Printing job 3: 3 pages
Nothing to print
Job 99 was added after job 1 was printed, and cut in front of jobs 2 and 3.
Question 1:
Answer. The printer always takes from the front, and urgent jobs go in at the front. On a VecDeque both are O(1): move head. On a Vec they're remove(0) and insert(0, ..), and each one shifts every waiting job by one slot, so O(n).
Question 2:
Answer. Keep a running total in the struct: a total: u32 field. add_job and add_urgent_job add to it, print_next subtracts the job it takes, and total_pages just returns it.
Activity 34: Trees on paper
Name:
Problem 1: draw a list (in lecture)
struct Node {
value: i32,
next: Option<Box<Node>>,
}
let b = Node { value: 9, next: None };
let a = Node { value: 5, next: Some(Box::new(b)) };
let list: Option<Box<Node>> = Some(Box::new(a));
- Draw the stack and the heap. Label every block.
- How many blocks are on the heap? How many would a list of a thousand nodes need?
- What does
len(&list)return, and how many times doeslenget called?
Answer.
Stack: Heap:
┌─────────────────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ main() │ │ value: 5 │ │ value: 9 │
│ └ list: Option<Box<Node>> │ │ next: Some(Box) │ │ next: None │
│ = Some(ptr) ─────────────┼──▶│ └ ptr ─────────┼──▶│ │
└─────────────────────────────┘ └──────────────────┘ └──────────────────┘
- Two blocks, one per node. A thousand nodes is a thousand blocks. Monday's
BinaryHeapof a thousand was one block 2.lenis called three times: on the 5, on the 9, and on theNoneat the end, which returns 0
Problem 2: BST, heap, both, or neither? (in lecture)
Tree A: Tree B: Tree C: Tree D:
10 50 9 10
/ \ / \ / / \
5 15 30 40 5 5 15
/ \ / / \ / \
1 7 12 10 20 1 12
- For each tree: a search tree, a max-heap, both, or neither? Give the reason in a few words.
- Tree C is small. Could you add a third node and keep it both? Where, or why not?
Answer.
- A: search tree only. Left of 10 is 5, 1, 7 and right is 15, 12. Not a heap: 15 is bigger than its parent. B: max-heap only. Complete, and every parent is >= its children. Not a search tree: 40 is in the right subtree of 50, and 40 < 50. C: both. 5 < 9 for the search tree, 9 >= 5 for the heap, and one left child keeps it complete. D: neither. 15 > 10 breaks the heap. 12 is fine next to 5, but it's in the left subtree of 10 and 12 > 10. The search-tree rule is about every ancestor.
- No. A right child would have to be bigger than 9 for the search tree and at most 9 for the heap. A child under 5 breaks completeness, since row 2 isn't full yet. "Both" tops out at two nodes.
Problem 3: trace a search and an insert
Start from this search tree. For each task, list the nodes you visit, in order.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
a. contains(&tree, 4). Which nodes, and what comes back?
b. contains(&tree, 11). Which nodes, and what comes back?
c. insert(&mut tree, 11). Which nodes, and where does 11 end up? Draw the tree after.
Answer.
a. 8 (4 is smaller, go left), 3 (bigger, go right), 6 (smaller, go left), 4. Found: true
b. 8 (right), 10 (right), 14 (left), 13 (left), then None. Not there: false
c. The same path as part b: 8, 10, 14, 13, then None to the left of 13. That's where the search fell off, so that's where 11 goes, as a new leaf:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
/
11
Problem 4: read one, write one
a. Here's len for the list, from lecture. Write sum for the tree: the total of every value in it.
fn len(list: &Option<Box<Node>>) -> usize {
match list {
None => 0,
Some(node) => 1 + len(&node.next),
}
}
fn sum(tree: &Option<Box<Node>>) -> i32 {
}
What does sum return for the tree in Problem 3? What's its Big-O, for n nodes?
Answer.
fn sum(tree: &Option<Box<Node>>) -> i32 {
match tree {
None => 0,
Some(node) => node.value + sum(&node.left) + sum(&node.right),
}
}
66 for Problem 3's tree. O(n): every node is visited exactly once, and there's no comparison to let us skip a subtree. Adding things up needs all of them.
b. Starting from an empty tree, insert 5, 4, 3, 2, 1 in that order. Draw the result. What's the height, and what does searching it cost?
Answer. Every value is smaller than the one before, so every insert goes left:
5
/
4
/
3
/
2
/
1
Height 5, for 5 nodes. It's a linked list leaning the other way from the lecture's, and search is O(n) just the same. This is why real search trees rebalance (see the lecture appendix on BTreeMap).
Problem 5: which structure?
For each one, pick BinaryHeap, a binary search tree (BTreeSet), or HashSet, and say in a few words why.
- A game server runs thousands of scheduled events. Every tick, it runs whichever is soonest.
- A card game keeps every card still in the deck, and needs to deal "the lowest card above a 7" and "the three highest cards" quickly, as the deck changes.
- Dealing cards: before handing one out, check whether it's already been dealt this hand.
Answer.
BinaryHeap. Just the "what's next?" question asked over and over, O(log n) per push and pop- A binary search tree. Both questions are about order, "above a 7" is a range, and the deck keeps changing, so a sorted
Vecwould cost O(n) per deal HashSet. Just "is this in here?" and nobody cares about order
Activity 35: Where does the boundary go?
Name:
You're shipping the sensor scoring program from today's lecture. Here it is, one box per piece.
You'll sort these twice, for two different callers.
The pieces
┌───────────────────────────────────────────┐
│ [1] │
│ struct Reading { │
│ id: u32, │
│ value: f64, │
│ baseline: f64, │
│ } │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [2] │
│ fn load_readings(path: &str) │
│ -> Vec<Reading> │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [3] │
│ fn parse_line(line: &str) │
│ -> Option<Reading> │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [4] │
│ fn score_one(r: &Reading) -> f64 │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [5] │
│ fn score_all(rs: &[Reading]) -> Vec<f64> │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [6] │
│ fn adjust(x: f64) -> f64 │
│ // caps a score at 100.0 │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [7] │
│ fn mean(xs: &[f64]) -> f64 │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [8] │
│ fn summary(rs: &[Reading]) -> Summary │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [9] │
│ const DRIFT_THRESHOLD: f64 = 0.05; │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [10] │
│ fn is_drifting(r: &Reading) -> bool │
└───────────────────────────────────────────┘
Part 1: a Rust caller (in lecture)
You're publishing this as a library crate. Somebody else's Rust project will add it to their Cargo.toml.
Sort all ten boxes into two piles, by number.
Public. You write pub on it, and you're promising to keep it:
Private. You can rename or delete it tomorrow:
People will disagree about one of these ten. Which one, and what's the argument on each side? Compare with a neighbor if you like.
Answer. Public: Reading (a caller needs the type to use anything else), load_readings, score_all, mean, summary, is_drifting.
Private: parse_line, adjust, and DRIFT_THRESHOLD. They're helpers for the main functions and we might want to change them later without breaking what gets used publically.
score_one is the contraversial one. Public is defensible: scoring a single reading is a reasonable thing to want, and it's hard to justify keepign score_one private if score_all is private. Private is defensible too, because publishing it invites callers to write their own loop over it, and we might later want to change internals around score_all.
Part 2: now a Python caller
Same code. Different person on the other side.
Your teammate has a pandas DataFrame with a value column and a baseline column, a million rows each, and a for loop over them that's the slowest step in their pipeline.
Re-sort the boxes. Which ones cross into Python?
Crosses:
Stays in Rust:
score_all can't cross in its current shape. Why not, and what would you change its signature to?
Answer. The set of public functions gets smaller.
load_readings and parse_line stay private. Pandas already loaded the file, and read_csv is compiled code underneat. mean stays too. NumPy has its own, and it's fast enough.
Reading doesn't cross, but then Python has no Reading. So score_all can't keep &[Reading]. It becomes:
fn score_all(values: Vec<f64>, baselines: Vec<f64>) -> Vec<f64>
summary and is_drifting could cross if you reshape them the same way
Part 3: two designs, same job
Two people on your team expose the scoring to Python in different ways.
Design A calls into Rust once per row.
import sensor_scoring
scores = []
for row in df.itertuples():
scores.append(sensor_scoring.score_one(row.value, row.baseline)) # 1,000,000 calls
Design B hands both columns over once.
import sensor_scoring
scores = sensor_scoring.score_all(df["value"].tolist(), df["baseline"].tolist()) # 1 call
Both produce the same numbers, and the Rust arithmetic inside is identical.
1. Predict: which is faster, and why?
2. One of these can end up slower than the plain Python loop it replaced. Which one, and how is that possible?
Answer. Design B. On a million readings we measured a plain Python loop at about 100 ms, Design A at about 115 ms, and Design B at about 28 ms.
Every trip across the boundary converts Python objects into Rust types, and back again on the way out. B pays that once, A pays it a million times.
Design A is the one that loses to plain Python. The conversion costs more than the subtraction it's wrapped around, so A added work to every row.
The rule: cross the boundary rarely, and carry a lot each time.
Part 4: back to week two (if there's time)
In week two we added up ten million numbers in Python and again in Rust, and Rust was around 350x faster.
Now you know how to use both in one program. Suppose that program also had to load its numbers from a CSV and plot the result.
Which pieces would you write in Rust, and which would you leave in Python?
Answer. Loading and plotting stay in Python. The ten-million-number loop goes to Rust, handed over in one call.
Lecture 1 - Welcome: what this course is, and why Rust
What today will look like
- Screen-free space
Agenda
- What is this course, and why Rust?
- Why are you taking it?
- Who we are, and how the class runs
- Grading, projects, and exams
- Syllabus review activity
Everything in 210 is in the service of (at least one of):
- Code development skills - tools and best practices
- Programming in Rust
- Systems concepts (memory, performance, types)
- Data structures and algorithms (to be continued in DS 320)
Why coding development skills matter
- Often never taught explicitly, can be tricky to self-teach
- Vitally important in "the real world", when you'll need to:
- Get out of a "detached head" state without losing your head
- Collaborate with others on code across space and time
- Work on massive codebases and data warehouses
- The more AI takes over the coding part, the more the layer around it matters
Why Systems Programming Matters
Knowing enough to answer
- Why is my code slow?
- Why is my app crashing?
- Why did we get hacked?
Or better yet... not having to answer those questions as often!
Why data structures and algorithms?
Knowing enough to answer
- Why is my model producing weird results?
- Is there a smarter way to do this than brute-force?
- How is this ever going to scale?
And inventing whole net new ways of working with data.
Also -
- Technical interviews
- Intellectual joy
Why are we doing this in Rust?
- A second language
- A compiled language
- A systems programming language
- A modern language
- An increasingly popular language
But why are YOU taking it?
I just want to say - I hear you. Here's my job...
Logistics
What have you heard about the course?
New(ish) Course Changes
- Local dev and focus on development skills
- Mastery vs coverage
- In-class activities in every lecture
- Close alignment between lectures, projects, and exams
- Three exams and code reviews to measure learning w/o AI policing
- Data structures and algs integrated, not tacked on
Why the shift to "active learning"?
- A meta-analysis of 225 studies found students in traditional lecture courses are 1.5 times more likely to fail compared to active learning environments.
- Active learning produces consistent effect sizes of 0.47-0.49 standard deviations, or half a letter grade improvement.
- Active learning reduces achievement gaps between underrepresented and majority students by 33-45%.
Our Teaching Staff
- Instructor: Lauren Wheelock
- Course assistants: Kesar Narayan, Lingjie Su
- A discussion TAs: Matt Morris (A2), Gabriel Burr (A3, A4)
- B discussion TAs: Emir Tali (B2), Kristen Bestavros (B3), Nia Naresh Kumar (B4)
Two things to know about me...
- I am your advocate.
- It's us against the material
- No gotchas
- Lots of practice and review in class
- Please share feedback
- I want to know who you are (coffee chats!)
- If you are struggling, please reach out early so we can help
- I have high expectations for you.
- Grading on an absolute scale (I try not to curve)
- Less weight on autograders, more on exams and code review
- When you're here, you're HERE (no laptops, activities, cold calling, print-outs)
- We will practice being uncomfortable and not knowing
- You CAN learn this stuff!
What this means for grading
50% exams: 15% midterm 1, 15% midterm 2, 20% final
20% active engagement: 15% in-class activities, 5% pre-work and surveys
15% code reviews: 5% each, three projects
15% autograded work: 5% each, three projects
Another way to look at it
35% is about EFFORT: participation, pre-work, coding to pass tests
65% is about MASTERY: exams and code reviews
Half of every project is a conversation
The code review is worth as much as every automated test combined.
Working code you can't explain, in this era, isn't worth much.
We'll share more and help you prepare as we go.
Attendance runs in three periods
- Period 1: Lectures 1-12, Discussions 1-3
- Period 2: Lectures 13-27, Discussions 4 and 7
- Period 3: Lectures 29-40, Discussions 9 and 11 and the skew-week
You can miss up to two lectures or one discussion per period for "free" - no need to explain or email me.
We use a bunch of tools for this: activity sheets, Gradescope tasks, cold-calling, headcounts
Exam dates, so you can check for conflicts
| Midterm 1 | Friday, October 9 | in class, your own section |
| Midterm 2 | Friday, November 6 | in class, your own section |
| Final | Monday, December 14, 12:00-2:00pm | CGS 505, both sections together |
Please check your finals schedule this week
The full finals schedule for all courses is published.
Look for two things:
- A direct conflict, two exams at the same time
- Three exams in a 24-hour window
If you find #1 or if 210 is the middle exam for #2 tell me (or your other instructors) ASAP.
Lectures
Mondays, Wednesdays, Fridays here in 871 Commonwealth Ave, CGS 505
- A1: 11:15am - 12:05pm
- B1: 12:20pm - 1:10pm
Lecture content will be the same, but you must attend the lecture you're registered for.
Discussion Sections
Section A - Wednesdays, 871 Commonwealth Ave CGS 525
- A2: 1:25 - 2:15pm, Matt
- A3: 2:30 - 3:20pm, Gabriel
- A4: 3:35 - 4:25pm, Gabriel
Section B - Tuesdays
- B2: 11:00 - 11:50am, MCS B31, Emir
- B3: 12:30 - 1:20pm, MCS B31, Kristen
- B4: 2:00 - 2:50pm, CDS 164, Nia
Section B discussions only run 50 min, underfilling the official slot, EXCEPT on code review days
You will:
- Get technical support and project help
- Attend code reviews and exam corrections
- Review material and get extra practice for exams
Discussions count towards attendance/participation and you must attend your assigned one.
Syllabus Review Activity
Instructions
In groups of 2-3, spend time answering the worksheet questions on paper.
Please turn in one sheet per group that includes all your names
Wrap up
Any questions from the activity you want to ask before Friday?
By Friday
Please fill out the intro survey linked in the email if you haven't so I can get to know you.
Your first pre-lecture task is due at 11am Friday.
Bring your laptop and come prepared to work with the shell next class!
Lecture 2 - Hello shell: talking to your computer
Announcements
Learning objectives for today
By the end of this lecture, you should be able to:
- Navigate your file system on the command line
- Create, copy, move, and delete files and directories at the command line
- Interpret file permissions
We will also discuss, but you are not responsible for:
- Use pipes and redirection for basic text processing
- Write simple shell scripts
We'll have one of these slides every lecture and it's a great way to check in on what material you're responsible for for exams!
Let's play a game
That was a conversation with a fixed vocabulary
take lamp worked, but grab lamp didn't.
- The game knows a finite list of verbs
- There is no menu showing you what they are
- Being close does not count
Your shell works exactly the same way.
Commands and arguments
The shell takes commands and arguments, same as the game.
pwd
cd Documents
cat notes.txt
The grammar is a command in English: VERB (NOUN). "run", "drink water", "open door"
pwd is a verb on its own. cd and cat want a noun.
Once you can read those, the weirder ones come apart the same way:
ls -la ~
ls is the command. -la and ~ are both arguments.
What is a computer terminal?
A terminal is an interface between you and a computer, that shows text you typed and text the computer generated back.
It looks pretty similar today as it did fifty years ago.
Let's open one
Demo time.
Shell, Terminal, Console, Command line... and what's Bash?

- The command line is the interface where you type commands to interact with your computer.
- The command prompt is the character(s) before your cursor that signals you can type and can be configured with other reminders.
- The terminal or console is the program that opens a window and lets you interact with the shell.
- The shell is the command line interpreter that processes your commands.
Terminals are more like applications and shells are more like languages.
Shell, Terminal, Console, Command line... and what's Bash?
BUT they are often used interchangeably in speech:
- "Open your terminal"
- "Type this command in the shell"
- "Run this in the command line"
- "Execute this in your console"
The distinction matters when something breaks. The rest of the time, nobody is careful.
FYI - None of this lecture is about Rust
- 1971: The Unix Shell
- 1989: Bash
- 2005: Git
- 2015: Rust
If any part of this course will be useful 30 years from now, it's this stuff.
(Your AI is using it all the time too!)
The file system and navigation
Where does a file actually live?
You save something "to your Desktop." Where is it?
Everything starts at the root
Root Directory (/):
In Linux, the slash character represents the root of the entire file system.
(On Windows you may see "C:", on Linux and macOS it's just "/".)
(We'll talk more about Windows in a minute)

Key Directories You'll Use:
/ # Root of entire system
├── home/ # User home directories
│ └── username/ # Your personal space
├── usr/ # User programs and libraries
│ ├── bin/ # User programs (like cargo, rustc)
│ └── local/ # Locally installed software
└── tmp/ # Temporary files
Navigation Shortcuts:
~= Your home directory.= Current directory..= Parent directory/= Root directory
Let's take a look / basic navigation demo
Demo time! Let's look around... and see if we can find the desktop
Maybe half of your interactions with the shell will look like:
pwd # Print working directory
ls # List files in current directory
ls -a # List files including hidden files
ls -al # List files with details and hidden files
cd directory_name # Change to directory
cd .. # Go up one directory
cd ~ # Go to home directory
Putting it together, can we get there?
Tips:
- Use
Tabfor auto-completion (great for paths!) - Use
Up Arrowto access command history - Try
control-cto abort something running or clear a line - You can't click into a line to edit it, use left/right arrows (or vim, or copy-paste)
Flags / Options
Special arguments called "options" or "flags" usually start with a dash - and can be separate or combined. These are equivalent:
ls -la
ls -al
ls -a -l
ls -l -a
BUT they typically need to come before other arguments:
ls -l -a ~ # works!
ls -l ~ -a # does not work
Understanding ls -la Output
-rw-r--r-- 1 user group 1024 Jan 15 10:30 filename.txt
drwxr-xr-x 2 user group 4096 Jan 15 10:25 dirname

(Don't worry about "groups"!)
We will see these kinds of permissions again in Rust programming!
Don't have permission? Don't tell anyone I told you this but...

What do you think sudo stands for?
Sorry, Windows users
- macOS is built on Unix, so its terminal already speaks bash
- Windows ships its own shells (Command Prompt, PowerShell), which use different names
dirinstead oflscopyandmoveinstead ofcpandmv
- We strongly recommend Windows users install a terminal with
bash(we'll do it today!) so we can speak the same language.
With Git Bash, Windows gets Unix tools, so ls, cp, mv, cat, and pwd work the same as on a Mac or Linux.
BUT anything owned by the OS (rather than the shell) is still different:
- macOS opens a file with
open - Windows uses
startorexplorer .
One thing is unavoidable and painful: different paths
/vsC:\Users\- This incompatibility has caused more suffering than metric vs imperial units.
Quiz time!
What do these stand for and what do they do:
pwdcdls
And
- How can you "get home quickly"?
These slides make a great starting point for Anki!
Reverse, reverse!
- How can you see the name of the directory you're in?
- How can you look around to see what's in the folder?
- How can you go into one of those folders?
- How can you back out?
- How can you see hidden files?
The rest of the 80% of bash commands you will mostly ever use
mkdir project_name # Create directory
mkdir -p path/to/dir # Create nested directories
touch notes.txt # Create empty file
echo "Hello World" > notes.txt # Overwrite file contents
echo "It is me" >> notes.txt # Append to file content
cat filename.txt # Display entire file
head filename.txt # Show first 10 lines
tail filename.txt # Show last 10 lines
less filename.txt # View file page by page (press q to quit)
nano filename.txt # Edit a file
cp file.txt backup.txt # Copy file
mv old_name new_name # Rename/move file
rm filename # Delete file
rm -r directory_name # Delete directory and contents
rm -rf directory_name # Delete dir and contents without confirmation
Three ways to go further
So far we've run one command at a time. We can build on that.
| a pipe sends one program's output straight into another program.
ls -la | sort -k5 -nr | head -10 # the ten biggest things here
> redirection sends it into a file instead. >> adds to the end rather than overwriting.
ls -la > results.txt
.sh a shell script is a saved copy-paste. Put your commands in a file, start it with #!/bin/bash, run it with source script.sh.
You do not need any of these today, but I'd bet you'll use all three eventually.
So what is all this good for?
Things you already know how to do, without the clicking
python3 analysis.py # Run a script. No IDE, no notebook
pip install pandas # You have done this one already
code . # Open this folder in VS Code
And things you probably did not know you could do from here:
open . # this folder, in Finder
open -a Spotify # launch an app
open "https://google.com/search?q=what+is+bash" # search the web
open is macOS. In Git Bash it is start, on Linux xdg-open.
For when your UI just won't cut it
# Rename 500 photos at once
for file in *.jpg; do mv "$file" "vacation_$file"; done
# Delete everything you have not touched in 30 days
find . -type f -mtime +30 -delete
# Why is my fan running like it is about to take off?
ps aux | grep app # Find that app that's hogging memory
df -h # See disk space usage immediately
# Find that file where you wrote something six months ago
grep -r searchterm . # this folder and everything under it
grep -r searchterm ~ # your whole home directory. Go get a coffee
In-Class Activity: Shell Challenge
Navigate to the course website for activity instructions.
https://rust4ds.github.io/ds210-fa26-lectures/activities/activity_2.html
Upload your work, however far you get, on Gradescope by the end of class.
You may discuss side-by-side but please each complete and submit separately.
Wrap up
Questions from the activity or anything today?
Coming up
- No class Monday, Labor Day
- Your first discussion meets Tuesday / Wednesday and it's an important one where you'll get help getting all your tools set up. If you miss it, you won't be ready for class Friday.
- Pre-lecture task due Wednesday (shell exploration)
- We start Rust on Wednesday! Get excited. Wear crab-themed attire. Or not. (That would be weird?)
- Next Friday: git and GitHub, and Project 1 goes out
Appendix: for reference, not covered in lecture
How does Shell find your commands and programs
python --version # checks what version of python we have
firefox # opens firefox!
When you execute a command, the shell looks for an executable file with that exact name in specific locations (folders).
which python
which firefox
These specific locations are defined by the PATH environment variable.
echo $PATH
Common Permission Patterns
644orrw-r--r--: Files you can edit, others can read755orrwxr-xr-x: Programs you can run or edit, others can read/run600orrw-------: Private files only you can access
(Any guesses about the numeric codes?)
Terminals and shells come in proper nouns
Terminals:
- Terminal (macOS)
- iTerm2 (macOS)
- GNOME Terminal (Linux)
- Konsole (Linux)
- Command Prompt (Windows)
- PowerShell (Windows)
- Git Bash (Windows)
Shells:
- Bash (Bourne Again SHell) - most common on Linux and macOS
- Zsh (Z Shell) - default on modern macOS
- Fish (Friendly Interactive SHell) - user-friendly alternative
- Tcsh (TENEX C Shell) - popular on some Unix systems
- PowerShell - advanced shell for Windows
Your shell profile
Your shell reads a configuration file when it starts up. This is where you can add aliases, modify your PATH, and customize your environment.
- macOS (zsh):
~/.zshrc - macOS (bash):
~/.bash_profileor~/.bashrc - Linux (bash):
~/.bashrc - Windows Git Bash:
~/.bash_profile
It is in your home directory.
# Check which shell you're using (macOS/Linux)
echo $SHELL
echo $HOME/.zshrc # macOS with zsh
echo $HOME/.bash_profile # macOS/Linux with bash
Adding aliases to your shell profile
# Edit your shell configuration file (choose the right one for your system)
nano ~/.zshrc # macOS zsh
nano ~/.bash_profile # macOS bash or Git Bash
nano ~/.bashrc # Linux bash
# Add these helpful aliases:
alias ll='ls -la'
alias ..='cd ..'
alias ...='cd ../..'
alias projects='cd ~/development'
alias grep='grep --color=auto'
# Custom functions
# This will make a directory specified as the argument and change into it
mkcd() {
mkdir -p "$1" && cd "$1"
}
Modifying your PATH
You may need to do this occasionally to make tools you install available on the command line.
# Add to your shell configuration file
export PATH="$HOME/bin:$PATH"
export PATH="$HOME/.cargo/bin:$PATH" # For Rust tools (we'll add this later)
Applying changes:
source ~/.zshrc # For zsh
source ~/.bash_profile # For bash
# Or start a new terminal session, or run: exec $SHELL
Lecture 3 - Hello Rust: your first program, and why it is fast
Announcements
Learning objectives
By the end of class today you should be able to:
- Explain what a compiler and a compiled language are
- Create a simple "hello world" Rust program with proper syntax (
fn, brackets) - Use
rustcandcargoto compile and run Rust programs - Explain what mutable and immutable variables are in Rust
Rust in three concepts
- Compiled
- Type-safe
- Memory-safe
What is a compiler?
Think for a moment, then turn to your neighbor: What is a compiler? What does it actually do?

A compiler translates your whole program into machine code once, ahead of time.
Your computer then runs the resulting machine code.
Python is interpreted instead: the interpreter reads your code and executes it line by line, every time you run it.
Type-safe and memory-safe
Type-safe
- Every value has a type, and the compiler refuses to mix and match
Memory-safe
- The compiler restricts what variables you can change and when to prevent a large class of issues with older languages
The same benefit:
- Issues that crash Python or C/C++ at runtime will be caught by Rust before anything runs
We'll understand this a lot more clearly as we go!
Demo: your first Rust project
cargo new hello_rust --vcs none
cd hello_rust
ls -a
What did that give us?
cat Cargo.toml
cat src/main.rs
cargo run
ls
Rust v Python
Rust v Python - Basic function writing
Rust
fn main() { println!("Hello, world!"); }
Python
def main():
print("Hello, world!")
main()
What differences do you notice?
fnkeyword for functions- Braces
{}for code blocks - Semicolons
;end statements println!is a macro (the!means macro) - more on this latermainruns on its own
Rust v Python - Variables, types, and mutability
RUN ME!
fn main() { let x = 5; // immutable by default let mut y = 10; // mut makes it mutable y = 15; // this works // x = 6; // this would error! // y = "today" // this would also error! println!("x is {}, y is {}", x, y); }
Key differences from Python:
- Python: everything mutable by default
- Rust: immutable by default with fixed types
Rust v Python: which one is the real thing?
If you haven't been bitten by python like this yet, you will.
a = [1, 2, 3, 4]
b = a[1:3] # slice a list
b[0] = 99
print(a) # [1, 2, 3, 4] unchanged
import numpy as np
c = np.array([1, 2, 3, 4])
d = c[1:3] # slice an array
d[0] = 99
print(c) # [1, 99, 3, 4] CHANGED
Same syntax. Opposite behavior.
Nothing in either line of code tells you which one to expect.
Show of hands for which you prefer?
In Rust you have to say which one you meant
let b = a; // move: a is gone, b owns it now
let b = a.clone(); // copy: two separate values
let b = &a; // borrow: b just looks at a
Three different behaviors. Three different notations.
It's always clear what's happening. You never have to wonder what b = a did.
Compiling and running
Rust works in two steps
Python: One Step (Interpreted)
python hello.py
- Python reads your code line by line and executes it immediately
- No separate compilation step needed
Rust: Two Steps (Compiled)
# Step 1: Compile (translate to machine code)
rustc hello.rs
# Step 2: Run the executable
./hello
rustcis your compiler that translates Rust program to machine code- Then you run the executable (why
./?)
Rust with Cargo (two-in-one)
# Set-up steps (one time)
cargo new my_project
cd my_project
# Build and run (compiles automatically)
cargo run
- Cargo uses
rustcunder the hood
Cargo has to be run from inside the project. If you see "could not find Cargo.toml", you are standing in the wrong folder. pwd to see where you are, cd to fix it.
Cargo can do it in two steps too
cargo build # compile only
./target/debug/my_project # run what it built
cargo run is those two commands in one.
You already saw both halves in the demo. cargo run compiled and ran it, then we went into target/debug and ran the executable ourselves, and got the same output.
Two steps or one. Same program either way.
Where do rustc and cargo actually live?
You typed rustc. You never said where it is. So how did the shell find it?
which rustc # /Users/you/.cargo/bin/rustc
which cargo # /Users/you/.cargo/bin/cargo
which ls # /bin/ls
They are files, sitting in a folder, exactly like everything you looked at on Friday.
When you type a command, the shell searches a list of folders for a file with that name. That list is an environment variable:
echo $PATH
# /Users/you/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin
Folders separated by colons, searched left to right. First match wins.
Installing Rust is mostly this: put some files in ~/.cargo/bin, then add that folder to your PATH.
Putting a folder on the PATH yourself
You will often do this when you install a new tool.
For this terminal window only:
export PATH="$HOME/my_tools:$PATH"
To make it permanent, put that line in the file your shell reads on startup, then open a new terminal:
nano ~/.zshrc # macOS
nano ~/.bash_profile # Git Bash on Windows
"command not found" usually means "not on the PATH", not "not installed". Check with which, then check echo $PATH, before you reinstall anything.
And that is why you had to type ./hello
Your current directory is not on the PATH.
So plain hello means "search the PATH folders", and it is not in any of them.
./hello means "the file called hello, right here."
So what does that buy us?
Adding up ten million numbers
The same program, written twice. Build a list of ten million numbers, then add them all up.
sum = 0
for number in numbers:
sum = sum + number
let mut sum = 0;
for number in numbers {
sum = sum + number;
}
Same answer, every time. How long should each one take? (Write your guesses)
Write a guess now. Fill in the rest as we go.
| Your guess | What it was | Notes | |
|---|---|---|---|
| Python | |||
Rust, cargo run | |||
Rust, cargo run --release |
Adding up ten million numbers
| Time | |
|---|---|
| Python | ~500 ms |
Rust, cargo run | ~40 ms |
Rust, cargo run --release | ~1.4 ms |
Around 350x faster.
--release tells the compiler to spend longer optimizing. The default build skips that so it compiles faster while you are working. We come back to it on Monday.
If you're a large tech company (like every AI company) this cuts your compute bill by billions of dollars.
Always use --release when evaluating your program's performance to get the best times!
Why is Rust faster than Python?
Python's python3 command is an interpreter.
It's like watching a speech in a foreign language with a live interpreter: it works, you understand it, but every sentence costs you the interpreter's time.
Rust translates the whole thing once, ahead of time, into the computer's own language. Then it just runs. No interpreter in the room.
In-Class Activity: put the program together
- Get in groups of 2-3
- Send one person up to get a packet
- Write your names on the submission sheet
Place the lines in order in two parts on the page: your shell, and your code file src/main.rs, to make a reasonable sequence and a working program.
Full instructions: Activity 3
Coming up
- If you need more help getting set up after discussion follow up on Piazza
- Friday: git and GitHub. We put this project under version control, and Project 1 goes out
- Monday we build a whole program start to finish
Lecture 4 - Hello git: save points for your code
Announcements
Git Concepts
Is this familiar to anyone?

Have you ever saved final_v2_ACTUAL.docx? What problem were you solving?
The problem with "manual" version control
- Storage space (due to redundancy)
- Hard to see what changes were made when
- Hard to collaborate (merge, review)
The collaboration problem

Learning Objectives
By the end of this lecture, you should be able to:
- Say why version control matters, and what it gives you that a folder of dated copies does not
- Configure git for first-time use
- Turn a project you already have into a repository, and clone one you don't
- See what you changed, and undo it
- Run the everyday loop:
status,add,commit,push - Connect a local repository to GitHub
This is a lot to take in at once, but we will be practicing and developing it ALL semester. Today we'll go over the loop you will run every day, and we'll talk about branches and merging on Monday.
One repo, two copies, and a staging area
Repository (repo). A project folder that git is tracking (your files plus their historical versions).
It can live in two places at once:
- Local is the copy on your laptop. This is the one you edit
- Remote is a copy hosted somewhere everyone can reach, usually on GitHub. Nobody edits this one directly
Most of your work happens locally. Only push and pull move work between the copies.
Staging: the batch you are about to save
Git does not save everything you changed. It saves what you chose.
Workspace. Your files as they are right now, mid-edit
Staging area. The batch you are assembling out of those edits
Commit. That batch, written into the project's history with a message on it
If you've ever looked at Google Doc histories, Google tries to detect periods of work automatically, but it never works quite right. This gives you control.
Staging is like attaching files to an email (kinda)
- Attaching the files is
git add. You pick what goes in. Attach the wrong file, take it off, attach a different one. Nothing is sent yet - The subject line is your commit message. It tells someone what is in here without making them open it
- Hitting send with your wifi off is
git commit. The batch is now a fixed record (an email in your outbox) but it hasn't actually left your machine yet - Connecting to wifi so your email goes out is like
git pushwhich sends your built-up commits up to GitHub for your collaborators to see
All analogies (like models) are wrong, but some are useful. With time and practice you'll get a feel for what these things really are and won't need the analogies anymore.
Git Workflows

More git concepts
Commit: A snapshot of your project at a specific moment, with a message explaining what changed.
Diff: The collection of specific edits in a commit. (Or generally, the differences between any two versions of a file.)
Branch: One "timeline" of commits that may diverge from other timelines

Not today. We come back to branching on Monday.
Essential Git Commands
One-Time Setup
You've done this already in discussion!
# Configure your identity (use your real name and email)
git config --global user.name "Your Full Name"
git config --global user.email "your.email@example.com"
# Set default branch name
git config --global init.defaultBranch main
Note: The community has moved away from
masteras the default branch name, but it may still be default in some installations.
Demo 1a: the project we made on Wednesday
Same command as Wednesday, so we start where you started:
cargo new hello_rust --vcs none
cd hello_rust
cargo run
ls -a # your files, and no .git anywhere
Right now it is just a folder. Let's make it a repository.
git init # now there's a .git folder. That IS the repository
git status # everything is untracked, and look what showed up
Save a baseline, so there is something to compare against later.
git add src/main.rs Cargo.toml Cargo.lock # notice what I am leaving out
git commit -m "Add the project cargo made in class"
git log
Demo 1b: change it, compare it, undo it
Now change one line in src/main.rs, and ask git what happened.
git status # now it says modified
git diff # here is exactly what I changed
That one is worth keeping, so it goes in the history the same way:
git add src/main.rs
git commit -m "Change the greeting to name the course"
git log # two commits now
Change it once more. This time we throw the change away.
git diff # the change is real
git restore src/main.rs # and here is how I take it back
git status # main.rs is back, as if it never happened
Demo 2a: making a change stick
# make a real change, then
git status
git add src/main.rs # move it to the staging area
git status # note that it says something different now
git commit -m "Pull the course name out into a variable"
git log # three commits now, yours on top
git push # ...and watch this fail
Demo 2b: there is nowhere to push to yet
git push cannot create a repository, so we will an empty one on GitHub first:
- Go to https://github.com/new
- Name your repo using your local folder's name (
hello_rust) keeps things simple - Choose public or private (I'll choose private)
- Leave README, .gitignore, and license off so that it starts truly empty
- Click Create repository. GitHub shows a page of commands with your URL already filled in
Then this should work
git remote add origin https://github.com/yourusername/repository-name.git
git push -u origin main
After that first push, plain git push is enough.
If you're missing a remote, git will throw an error and prompt the git remote add line line:
fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using
git remote add <name> <url>
And if there's a renote but no tracked branch it will say:
fatal: The current branch main has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin main
(git push -u origin main is just shorthand for git push --set-upstream origin main)
Where does everyone else's code come from?
What if you want to build upon someone else's code?
You can't edit it / push to it because you don't have write access
So you take a copy that is yours. That is a fork (or a template copy).
It's like when you get view-only access to a Google Doc and you can't edit it until you "make a copy".
A fork is your own copy of someone else's repository that you can edit. A template copy is like a fork but private and won't be used to push back to the upstream repo.
Projects are submitted by giving us the URL of your copy.
Fork copies sideways. Clone copies down.
- Fork starts on GitHub, stays in GitHub
- Clone happens in the terminal. Your repo on GitHub becomes a folder on your laptop
Demo 1a went the other direction: a folder you already had became a repository. Cloning is how you start when the project already exists.
Cloning, which you do in the activity
git clone <the URL of your fork>
cd <the folder it just made>
ls -a # .git is already here. You did not run git init
git remote -v # and origin is already set. You did not add it
git log # somebody else's history, now on your machine
Cloning does for you what we did by hand in Demos 1a and 2b. You never run git init, and you never add a remote.
git clone downloads to wherever you are, so run pwd before you clone and make sure that's where you want the project to live.
Writing Good Commit Messages
- Start with a present / imperative verb
- Be brief and specific
- If you find yourself using "and" a lot your commits are too big
The Golden Rule: Your commit message should complete this sentence: "If applied, this commit will [your message here]"
Good Examples:
git commit -m "Add input validation for calculator"
git commit -m "Fix division by zero error"
git commit -m "Refactor string parsing for clarity"
git commit -m "Add tests for edge cases"
Bad Examples:
git commit -m "fix a bug" # What bug?
git commit -m "fix date range bug and added multi-user feature" # Too much at once
git commit -m "trying again" # What are you doing differently?
So about that target/ folder
You saw it in git status.
It holds thousands of files, up to hundreds of MB, and none of it is yours.
cargo build regenerates every bit of it from src/ and Cargo.toml.
So you don't want to keep track of it!
Anything in your repo you DON'T want tracked goes in a file called .gitignore:
target/
.DS_Store
.vscode/
.ipynb_checkpoints/
Then git status stops mentioning it and git add stops picking it up.
The rule: if a file can be regenerated, don't commit it. If you run git add and see a pile of files you don't recognize, it's time to update your .gitignore.
cargo new actually writes a .gitignore containing /target for you and runs git init unless you tell it not to. We told it not to (this time) so that you could see how it all works!
When a tool refuses, read what it says
Twice we saw git refuse to do something, but then it printed the exact command that fixed it.
This is why we love error messages!
Read the whole message before you change anything, and before you search. The answer is usually right in front of you.
Rust's compiler is the best example of this. Its errors are long because they are trying to help. We'll practice with this soon.
What we still owe you
Today was the loop you run every day, by yourself:
clone or init, change something, diff, add, commit, push
Still to come, starting Monday:
- Branches, so two people can work together without stepping on each other
- Merging, and what happens when git cannot figure it out for you
- Pull requests, which is how people review each other's code
You'll need merging for Project 1, and we recommend learning to use branches and PRs there too but won't require them until Project 2.
Getting unstuck
"What's going on??"
git status # use it until it's a reflex!
"I made a mistake in my last commit message"
git commit --amend -m "Corrected commit message"
"I want to undo a git add"
git restore --staged filename.rs
"I want to throw away changes I haven't committed yet"
git restore filename.rs # one file
git reset --hard # ALL uncommitted changes (CAREFUL!)
"I want to do something else"
git log # shows commit history
git branch # shows available branches
Search and Stack Overflow are your friends here. So is git status, which is unusually good at telling you what to do next.
In-Class Activity: your first repository
Open your laptops and navigate to https://rust4ds.github.io/ds210-fa26-lectures/activities/activity_4.html for instructions.
Coming up
- Project 1 is out today. Checkpoint 1 is due Fri Sep 18, and today's activity is a head start
- Monday: reading, modifying, and breaking Rust. Also branches, merging, and what a merge conflict looks like
- Remember to complete the pre-lecture task for Monday!
Appendix: reference, not covered in lecture
We will go into git branching, merging, and pull requests more next lecture. Some notes here for your reference if you want a complete picture of git now.
Git Branching
-
Main branch: Usually called
main(ormasterin older repos) -
Feature branches: Created for new features or bug fixes
-
Isolates experimental work
-
Enables parallel development
-
Facilitates code review
Merging and Pull Requests
Merge: Combines changes from different branches. Takes commits from one branch and integrates them into another branch.
Merge Conflict: Merging may fail if both branches change the same lines. Git will point to the conflict and ask you to resolve it before finishing the merge.
Pull Request (PR): A request to merge your changes into another branch, typically used for code review. You "request" that someone "pull" your changes into the main codebase.
The branching workflow
# Create a descriptive branch name for the change you want to make
git checkout -b feature_branch
git status # See current state
git add filename.rs # Add specific file to staging
git add . # Add all changes in current directory
git commit -m "Add calculator function"
git checkout main # Switch back to main
git merge feature_branch # Merge branch back into main
# merge merges the branch you NAME *into* the branch you're currently ON
Keeping in sync
cd repository
git pull # get any changes from GitHub
git push # send your commits to GitHub
git fetch is like git pull but stops short of merging what it downloaded. git rebase is an alternative to git merge with different history-rewriting behavior.
Resources for learning more and practicing
- Interactive online git tutorial that goes a bit deeper: https://learngitbranching.js.org/
- A downloadable app with tutorials and challenges: https://github.com/jlord/git-it-electron
- Another good tutorial (examples in Ruby): https://gitimmersion.com/
- Pro Git book (free online): https://git-scm.com/book/en/v2
Lecture 5 - Start to finish: build, break, fix
Announcements:
Three tools, one workflow
- The shell (Lecture 2), to move around and run things
- Rust and Cargo (Lecture 3), to build a program
- Git (Lecture 4), to keep its history
Today we walk through using all three together, start to finish, to see how they work together (and fit in a bit of review)
The loop
Everything you do for the rest of this course is some version of this:
- Write a little
cargo run- Notice it doesn't compile!
- Read what the compiler said
- Fix it
cargo runand it works!cargo testand it passes the tests!git add .,git commit -m "..."git pushso work is saved
Step 3 is not failure. It is the normal state (SNAFU), and today we'll learn to love those errors (at least a little)
Learning objectives
By the end of this lecture, you should be able to:
- Start from scratch and make a rust program with history: make it, run it, break it, fix it, commit it, push it
- Read a Rust compiler error: find the code, the line, and the suggested fix, and know that the fix does not always belong on the line the error names
- Know the shell, git, and cargo commands you are responsible for
- Make a branch, open a pull request, and merge it back
- Undo a bad commit with
git revert, and say why that is safer than deleting it from history
What you're accountable for
The shell commands you should know
Move around and look:
pwdls(plusls -aandls -l)cd(pluscd ..andcd ~)catwhich
Make and change things:
mkdir,touch,cp,mv,rm(andrm -rf)echo "some words" >> filename.txtas a way to append text to a filenano
The git commands you should know
Starting a repository:
git init- The concept of
git clone(you'll usually copy the command from github)
The everyday loop:
git status,git add,git commit -m,git push,git pull
Looking at what changed:
git log,git diff
Fixing things
git restore,git revert
Working with other people:
git branch,git checkout,git merge
Cargo and rustc
cargo newcargo build,cargo run,cargo checkcargo testcargo run --releaserustc
Let's practice!
The program from Wednesday (with a bug)
fn main() { let scores = vec![85, 92, 78, 96]; scores.push(88); let total: i32 = scores.iter().sum(); let average = total as f64 / scores.len() as f64; if average >= 90.0 { println!("Excellent! Average: {:.1}", average); } else if average >= 80.0 { println!("Good work! Average: {:.1}", average); } else { println!("Keep trying! Average: {:.1}", average); } }
Notes:
Breaking down the compiler error
error[E0596]: cannot borrow `scores` as mutable, as it is not declared as mutable
--> src/main.rs:3:5
|
3 | scores.push(88);
| ^^^^^^ cannot borrow as mutable
|
help: consider changing this to be mutable
|
2 | let mut scores = vec![85, 92, 78, 96];
| +++
Every compiler error has the same five parts:
- An error code, like
E0596. You can look it up:rustc --explain E0596(or google it!) - A one-line summary of what is wrong
- Where it happened, as
file:line:column - Your code, with a caret pointing at the exact spot
- Usually, a suggested fix
Rust's error messages are unusually good. They are long because they are trying to help!
Demo: let's fix it (and break it again)
Notes:
Commit when something works, not when you take breaks. Let it feel like a little celebration, patting yourself on the back for building or fixing something.
Now the fun part: how to get ourselves out of trouble
But now if we...
cargo run
Oh no! We saved a bug in our last commit and we kept going! Let's find what went wrong
git log --oneline # find the commit that did it
How do we "undo a commit"? It's safer not to... instead we
git revert a1b2c3d
This makes a new commit that undoes what that old commit did. The bad commit stays in the history, and so does the fact that you undid it.
Why we do this:
- Your history stays honest
- It won't collide with someone else's work
(Yes there is a way to truly delete a commit, git reset --hard, but it's generally not best practice so you don't need to learn it)
A branch is somewhere to work without breaking main

main is the version that works. A branch is a second timeline where you can make a mess.
git branch # which branches exist, and where you are
git checkout -b add-letter-grades # make one and switch to it
# edit, cargo check, commit as usual
git push -u origin add-letter-grades
Nothing you do on the branch touches main until you ask for it.
You'll get hands-on practice with branching this week in discussion!
A pull request is how you ask to bring it back

On GitHub, open a pull request from your branch into main:
- It shows the diff. Exactly what would change, nothing hidden
- Somebody reads it and comments (this is why we do it!)
- When everyone is happy, merge, and the branch's commits join
main - Back in the terminal:
git checkout main, thengit pull
Let's try it.
Working with AI without wasting the semester
Your guesses to the mystery question:
How to code with AI and still learn something
Imagine you're learning French and typing your first awkward essay. Every time you start typing a sentence, something completes it for you, perfectly, with flawless grammar.
What are you learning?
You've learned how to use autocomplete. You are not learning French.
How would you use AI or other tools to learn a language?
(A few volunteers?)
Where AI hurts you in this course
You are here to learn Rust, and systems, and data science, not autocomplete.
So my number one suggestion is... Turn off autocomplete.
It stops you from being uncomfortable. It stops you from struggling.
Discomfort is what learning feels like. So it stops you from learning.
(Like exercise!)
Actionably:
- Turn off copilot suggestions (VS Code ships with that on!) (click on the robot in the bottom right and hit "disable completions")
- Tell your AI (Cursor, Claude Code, Copilot) to answer your questions but not edit your file directly
Where AI helps you in this course
Good places to use it:
- "What does this compiler error mean?"
- What's the name of the function that does x?
- Do you have feedback on how I wrote this? once it already works
- "Explain this concept a different way" when lecture wasn't enough
In every case you did some thinking first and you can tell whether the answer is any good. You won't blindly accept a bad answer
A workflow that actually works
- Think on paper. What is this supposed to do? What are the steps?
- Write the steps out in plain English, in comments, before any Rust (this is called "pseudocode")
- Write what you can.
- Then ask for help with the specific thing you're stuck on
- Read the answer until you could have written it. If you can't, ask about what you don't understand
Remember, for code review, you need to be able to explain everything you wrote!
In-Class Activity: compiler error hunt
So we're going to hold back on some tools for this one.
Install still not working? You can still do the activity
The Rust Playground compiles and runs Rust in your browser. Nothing to install, nothing to configure.
It is not a substitute for a real setup, and you will need one for Project 1. But we'll often use this for activities because:
- It's faster to get started
- It doesn't have rust-analyzer
Instructions
Working in pairs, in the Rust Playground ^
Program and instructions: https://rust4ds.github.io/ds210-fa26-lectures/activities/activity_5.html
- Paste the program in and Run it, so you know it works to start with
- Make one change at a time that breaks it. Misspell, delete, reorder, change a type
- Run it and read what comes back
- Write it on your half sheet: what you changed, and what the compiler said
- Undo it, and break it a different way
Goal: at least 8 different errors. There is room for 12 on your sheet if you get on a roll.
Debrief
-
Which error was the most confusing?
-
Which error message was the most helpful?
-
Did any errors surprise you?
-
Anything you thought would produce an error that didn't?
-
Let's make a list together. How many did we find?
Coming up
- Discussion this week is git practice: branches, merging, and what to do when git cannot merge two changes by itself
- Wednesday: variables and types. We start writing our own Rust rather than editing someone else's
- Project 1 checkpoint 1 is due Friday
Lecture 6 - Variables: types and their properties
Announcements
Learning Objectives
By the end of this lecture, you should be able to:
- Use the
mutkeyword and shadowing withletto modify variables - Declare constants using
const - Understand Rust's basic types and their sizes (ints, floats,
bool,char,&str) - Use type annotation (with
let), type conversion (as), and type inference - Work with boolean values using comparisons (
==,!=,<,>=) and logical operators (&&,||,!)
Variables and Mutability
Variables are by default immutable!
Let's try this and then fix it.
fn main(){ let x = 3; x = x + 1; println!("{x}") }
Why can't we do this now?
fn main(){ let mut x = 3; x = 9.5; println!("{x}") }
One way to fix - Variable shadowing: new variable with the same name
fn main(){ let solution = "4"; let solution : i32 = solution.parse() .expect("Not a number!"); let solution = solution * (solution - 1) / 2; println!("solution = {}",solution); let solution = "This is a string"; println!("solution = {}", solution); }
Variables vs Constants
Sometimes you need values that never change and are known at compile time:
#![allow(unused)] fn main() { const MAX_PLAYERS: u32 = 100; const PI: f64 = 3.14159; const GREETING: &str = "Hello, world!"; }
Constants:
- Are always immutable (no
mutallowed) - Use
constinstead oflet - Must have explicit types
- Named in
ALL_UPPERCASEby convention - Can be declared in any scope (including global)
- Must be computable at compile-time (so typically hard-coded)
When to use constants vs variables:
- Constants: Mathematical constants, configuration values, limits
- Variables: Data that might change or is computed at runtime
Types
Integers and Binary representations
Representing 13:
- In decimal (base 10): 13 = 1×10¹ + 3×10⁰
- In binary (base 2): 1101 = 1×2³ + 1×2² + 0×2¹ + 1×2⁰ = 8 + 4 + 0 + 1 = 13
For example, the number 13 in binary is 1101:
Binary: 1 1 0 1
Position: 3 2 1 0
2x^n: 8 4 2 1
Value: 8 4 0 1 → 8+4+1 = 13
T/P/S - What's the largest integer we can represent with 4 binary digits?
Bits and bytes
- Bit: The smallest unit of data in computing - can store either 0 or 1
- Byte: A group of 8 bits, which can represent 2⁸ = 256 different values (0-255)
- Computers typically address memory in byte-sized chunks
- (In sizes like "16 GB of RAM" GB refers to "gigaBYTES" not gigaBITS)
So what are ints, under the hood
Unsigned integers are stored in binary format.
But (signed) integers are stored in two's complement format, where:
- if the number is positive, the first bit is 0
- if the number is negative, the first bit is 1
To calculate the two's complement of a negative number, we flip all the bits and add 1.
Let's try it:
// binary representation of 7 and -7 println!("{:032b}", 7); println!("{:032b}", -7);
Why Two's Complement?

Integers come in all shapes and sizes
- unsigned integers:
u8,u16,u32,u64,u128,usize(architecture specific size, default for.len())- from to
- signed integers:
i8,i16,i32(default),i64,i128,isize(architecture specific size)- from to
These numbers (like u16) refer to bits, not bytes!
Different types don't play nice together
fn main(){ let x : i16 = 13; let y : i32 = -17; println!("{}", x * y); // will not work // println!("{}", (x as i32)* y); }
if you need to convert, use the as operator
Be careful with math on ints
u8 is 8 bits and can store maximum value 2^8 - 1 = 255.
If we multiply: .
How many bits do we need to store this value? We can take the log base 2 of the value.
fn main(){ let a: u8 = 255; let product = a as u32 * a as u32; // why u32? let's change it! println!("{} * {} = {}", a, a, product); println!("log base 2 is {}", (product as f64).log2()); }
So we need 16 bits to store the product of two u8 values.
In general when we multiply two numbers of size bits, we need bits to store the result.
Types - Floats
Why are they called floats?
- Two kinds:
f32andf64(default) - What do these mean?
Sizes of floats
#![allow(unused)] fn main() { println!("F32 min is {} max is {}", f32::MIN, f32::MAX); println!("F32 min is {:e} max is {:e}", f32::MIN, f32::MAX); println!("F64 min is {:e} max is {:e}", f64::MIN, f64::MAX); }
Why these sizes?
f32: 1 sign bit + 8 exponent bits + 23 significance bitsf64: 1 sign bit + 11 exponent bits + 52 significance bits
You don't always have to write the type, but there is always a type
fn main(){ let count = 42; let price = 19.99; let name = "DS210"; println!("{count}, {price}, {name}"); }
Nothing here says i32, f64 or &str.
Each of those vars has exactly one though, decided at compile time.
Rust (often) works out types from the value and what you do with it later.
When it can't it will let you know (with an error).
Your editor will tell you what Rust worked out
rust-analyzer writes the type in next to each let, greyed out, as though you had typed it yourself.

Floats and Rust's type inference system
fn main(){ let x:f32 = 4.0; let y:f32 = 4; // Will not work. It will not autoconvert for you. let z = 1.25; // won't get automatically assigned a type yet println!("{:.1}", x * z); //println!("{:.1}", (x as f64) * z); }
Two ways to put a variable in println!
#![allow(unused)] fn main() { let name = "Ada"; let age = 20; println!("{} is {}", name, age); // separate arguments, filled in order println!("{name} is {age}"); // the name goes inside the braces }
Both print Ada is 20. You'll see both styles.
Only a plain variable name fits inside the braces. For anything else, use {} and pass it separately:
println!("{age + 1}"); // compiler error
println!("{}", age + 1); // fine
Formatting in println!
You can control how numbers are displayed using format specifiers:
#![allow(unused)] fn main() { let total = 21.613749999999997; let price = 19.99; let big_number = 1_234_567.89; let small_number = 0.000123; let count = 42; // Float formatting println!("Default: {}", total); // Default: 21.613749999999996 println!("2 decimals: {:.2}", total); // 2 decimals: 21.61 println!("Currency: ${:.2}", price); // Currency: $19.99 // Scientific notation println!("Scientific: {:e}", big_number); // Scientific: 1.23456789e6 println!("Scientific: {:.2e}", small_number); // Scientific: 1.23e-4 // Integer formatting println!("Default: {}", count); // Default: 42 println!("Width 5: {:5}", count); // Width 5: 42 println!("Zero-pad: {:05}", count); // Zero-pad: 00042 println!("Binary: {:b}", count); // Binary: 101010 println!("Hex: {:x}", count); // Hex: 2a }
We won't expect you to memorize those - if you need them on an exam we'll give them to you in an appendix!
Mini-Quiz
Take a minute to talk to a partner about what these do, then I'll call on you
cargo new my_projectcargo checkgit add .rustc hello.rsgit pullcargo run --releasegit commit -m "fix bug"
Types - Booleans (and logical operators)
booluses one byte of memory (why not one bit?)
#![allow(unused)] fn main() { let x = true; let y: bool = false; println!("{}", x && y); // logical and println!("{}", x || y); // logical or println!("{}", !y); // logical not }
FYI there are "bitwise" operators that use single symbols (& and |) and also do binary arithmetic... but you won't need them. Just remember to use double && and || by default!
Comparisons give you a bool
#![allow(unused)] fn main() { let age = 20; println!("{}", age == 20); // equal println!("{}", age != 21); // not equal println!("{}", age >= 18 && age < 21); // combine them with && and || }
Also <, >, <=, >=, same as Python.
= sets a value, == asks a question. if age = 20 gives a compiler error.
One more shortcut, also the same as Python:
#![allow(unused)] fn main() { let mut count = 0; count += 1; // same as count = count + 1 count -= 1; // same as count = count - 1 }
(but Rust doesn't have count++)
Types - Characters
chardefined via single quotes, uses four bytes of memory (that's how many bits?)- For a complete list of UTF-8 characters check https://www.fileformat.info/info/charset/UTF-8/list.htm
#![allow(unused)] fn main() { let x: char = 'a'; let y = '🚦'; let z = '🦕'; println!("{} {} {}", x, y, z); }
Try Control-Command-Space (Mac) or Windows-Key + . (Windows) to add emojis anywhere!
Types - Strings
- A string slice (
&str) is defined via double quotes - A
String(with a capital S!) is something different - We'll talk a lot more about the difference later. Until then, you'll primarily use
&strand we'll try to steer you away from trouble.
fn main() { let s1 = "Hello! How are you, 🦕?"; // type is `&str` let s2 : &str = "Καλημέρα από την Βοστώνη και την DS210"; // here we make the type explicit println!("{}", s1); println!("{}\n", s2); // This doesn't work. You can't do String = &str //let s3: String = "Does this work?"; let s3: String = "Does this work?".to_string(); println!("{}", s3); let s4: String = String::from("How about this?"); println!("{}\n", s4); let s5: &str = &s3; println!("str reference to a String reference: {}\n", s5); // This won't work. // println!("{}", s1[3]); // println!("{}", s4[3]); // But you can index this way. println!("4th character of s1: {}", s1.chars().nth(3).unwrap()); println!("3rd character of s3: {}", s4.chars().nth(2).unwrap()); }
Activity time!
Tear off the last sheet in your packet. Instructions are there.
You can work in small groups but EACH person needs to fill in a sheet.
Make hypotheses for everything before breaking out laptops to test!
Lecture 7 - Functions: parameters, returns, and expressions
Announcements
Learning Objectives
By the end of this lecture, you should be able to:
- Write function signatures including parameter names, types, and return types
- Return more than one value from a function by returning a tuple
- Create functions that return the unit type
()for side-effect-only operations - Explain the difference between an expression and a statement in Rust
- Pass parameters into functions via copying, borrowing, and passing ownership
Function Syntax
We've seen a few examples like this:
#![allow(unused)] fn main() { fn my_age_in_5_years(age: i16) -> i16 { let new_age = age + 5; return new_age; } }
General function template:
#![allow(unused)] fn main() { fn function_name(arg_name_1:arg_type_1,arg_name_2:arg_type_2) -> type_returned // ^ This part is the "function signature" { // Do stuff // return something } // ^ This part is the "function body" and can be a statement or expression inside }
Where you put it does not matter. Rust sees every fn in the file wherever it sits, so main can call a function written below it (couldn't in Python!)
The signature is the function's "promise"
#![allow(unused)] fn main() { /// Returns the distance between two points on a line. fn distance(a: f64, b: f64) -> f64 { (a - b).abs() } }
The signature tells you what goes in and what comes out.
The /// above it is called a "doc comment" or "docstring" and it tells you what the function is for. (Your editor keeps the /// going when you press Enter)
Naming a function is naming its contract. If you can't keep it brief, the function is probably doing more than one job!
You will run into other comment-looking things in Rust code: /* */, /** */, //!. You don't need any of them in this course, and you can look them up if you see them.
Statements and expressions
Just as in math when we have:
- expressions like ()
- and equations like ()
In rust we have expressions and statements
- Expressions simplify to a value (like a math expression)
- Statements do things but don't simplify to a value (kind of like an equation?)
So -
y + 2is an expressionlet x = y + 2;is a statement
Statements and expressions can be nested
let x = y + 2; is a statement BUT it INCLUDES y + 2 which is an expression
The reverse is also true - we can build complex expressions that include statements
#![allow(unused)] fn main() { let y = { let x = 2 * 3; x }; }
A statement or expression - shout it out
let x = 5; // Statement or expression?
x + 2 // Statement or expression?
println!("hello"); // Statement or expression?
my_function(5) // Statement or expression?
let y = x + 2; // Statement or expression?
{
let z = 10; // Statement or expression?
z * 2 // Statement or expression?
} // Statement or expression?
return x + 5; // Statement or expression?
let x = {
println!("doing work"); // Statement or expression?
42 // Statement or expression?
}; // Statement or expression?
Maybe it was too easy to cheat because...
- Statements always end with semicolons
- Expressions never end with semicolons
So {} blocks are expressions too. They evaluate to their final line, as long as it has no semicolon.
Adding a semicolon turns an expression into a statement
fn main(){ let a = { let x = 10; x + 5 // Expression }; println!("{}",a); let b = { let x = 10; x + 5; // Statement }; println!("{:?}",b); }
That little {:?} makes things that don't normally print, print anyway! It's called "debug printing" and we'll see it more later.
Let's look at return again now
We have two ways of returning from a function:
#![allow(unused)] fn main() { fn my_age_in_5_years(age: i16) -> i16 { let new_age = age + 5; return new_age; } }
We can also:
#![allow(unused)] fn main() { fn my_age_in_5_years(age: i16) -> i16 { let new_age = age + 5; new_age } }
T/P/S - Why are these effectively the same thing? (Hint: think about expressions and statements)
Returning more than one thing
A function returns one value. But that one value can be a tuple, which groups several values together:
/// Returns the smallest and largest of three numbers. fn min_max(a: i32, b: i32, c: i32) -> (i32, i32) { let smallest = a.min(b).min(c); let largest = a.max(b).max(c); (smallest, largest) } fn main() { let (lo, hi) = min_max(14, 3, 27); println!("range: {} to {}", lo, hi); let t = min_max(14, 3, 27); println!("range: {} to {}", t.0, t.1); println!("{:?}", t); }
(i32, i32) is the return type: two integers, in that order.
Then we can unpack with let (lo, hi) = ... to split it back into two names.
You can reach into a tuple by position with .0 and .1, and {:?} prints the whole tuple at once.
But what happens if you don't return anything?
fn say_hello(who:&str) { // no -> return_type here // vs fn say_hello(who:&str) -> () { println!("Hello, {}!",who); } fn main() { say_hello("world"); say_hello("Boston"); say_hello("DS210"); // let z = say_hello("DS210"); // println!("The function returned {:?}", z) }
Functions that return no value
Functions that don't return or end in an expression return "the unit type" ()
() is an empty tuple that takes no memory (think of an empty set!)
This lets us have "side-effects only" functions that perform actions (printing, file I/O, etc.)
Pure, or side effects?
#![allow(unused)] fn main() { // Pure: same inputs, same answer, and nothing else happens fn add(x: i32, y: i32) -> i32 { x + y } // Side effect: it also prints, and the signature does not tell you that fn add_and_print(x: i32, y: i32) -> i32 { let result = x + y; println!("{} + {} = {}", x, y, result); result } }
A pure function is easier to test and easier to trust, because nothing outside it changes.
Both are fine. Just know which one you are writing.
Passing parameters
Here's where we get a preview of the memory stuff we'll really digest later.
3 ways to pass parameters
- Copying a parameter (default for
i32,bool,f64, other basic types) - Take ownership of a parameter (so it can change) (default for
String, other complex types) - Borrowing a parameter (to "peek" at it) (
&str,&i32)
Examples:
#![allow(unused)] fn main() { fn greet_person(first_name: String, last_name: &str, age: u32) { // first_name now OWNS what was passed to it // last_name is BORROWING what was passed to it // age COPIED what was passed to it println!("Hello, {} {}! You are {} years old.", first_name, last_name, age); } }
We'll talk a lot more about owning vs borrowing later. For now, some simple rules to get started:
Quick Rules for Beginners:
- Use
&strfor string parameters - Basic types like
i32,f64,boolare automatically copied - no worries there - Use
&before the parameter type when you don't need to modify it - If Rust complains about ownership, try following its suggestion or adding
& - You typically can't use a reference (
&) in a return value - that's why you'll seeStringas a return type more often than&str
Examples:
fn print_name(name: &str) { /* name is borrowed - original still usable */ }
fn calculate_area(width: f64, height: f64) -> f64 { /* both copied */ }
Just enough if to get through the activity
We've glossed over this so far. Here is the shape of it, and we do branching properly next lecture.
Syntax:
if condition {
//
} else if other_condition {
//
} else {
//
}
else ifandelseparts optional
Bringing it together with expressions
You can even use conditional expressions as values!
Python:
z = 100 if x == 7 else 200
Rust:
#![allow(unused)] fn main() { let x = 4; let z = if x == 7 {100} else {200}; println!("{}",z); }
// won't work fn main(){ let x = 4; println!("{}",if x == 7 {100} else {1.2}); }
Activity time!
We'll have our first hand-coding practice session!
You can work next to someone but write out your own sheet.
If you worked with someone, swap with someone else for feedback.
We'll go over answers at the end or start of next class.
Lecture 8 - Control flow: branching and looping
Announcements
Learning Objectives
- Write
if/else if/elsebranches and early returns - Use
while,for,loop,break, andcontinue - Use
forloops with ranges (..and..=) - Use
.iter()and.iter().enumerate()to loop over an array - Create and work with fixed-size arrays
- Choose appropriate loop types based on use case requirements
Three rules for branching with if
You probably already do these two:
- Indent each block. Rust doesn't need the whitespace to run, but people need it to read. Your editor will mostly take care of it. (Unless you're doing the all-on-one-line trick)
- Use
else ifrather than anifnested inside anelse
if x == 7 {
let z = 100;
} else {
let z = 200;
}
or
let z = if x == 7 {100} else {200};
This one takes some explaining:
- Keep nesting shallow. When it makes sense, return early, or move a branch into its own function
Checking inputs with nested if
#![allow(unused)] fn main() { /// Returns the score as a percentage, or -1.0 if the inputs don't make sense. fn percent(points: f64, max_points: f64) -> f64 { if max_points > 0.0 { if points >= 0.0 { if points <= max_points { points / max_points * 100.0 } else { println!("Invaid"); -1.0 } } else { println!("Invalid"); -1.0 } } else { println!("Invalid"); -1.0 } } }
Same checks, returning early
/// Returns the score as a percentage, or -1.0 if the inputs don't make sense. fn percent(points: f64, max_points: f64) -> f64 { if max_points <= 0.0 { println!("Max points must be positive"); return -1.0; } if points < 0.0 { println!("Points can't be negative"); return -1.0; } if points > max_points { println!("More points than the max"); return -1.0; } points / max_points * 100.0 } fn main() { println!("{}", percent(45.0, 50.0)); println!("{}", percent(55.0, 50.0)); }
Each check gets its own if, with its message right under it. Once you're past all of them, the inputs are good.
Your turn: clean this up
#![allow(unused)] fn main() { // This is technically valid but TERRIBLE code please DO NOT DO THIS let x = 4; let result = if x > 0 { if x < 10 { let temp = x * x; let bonus = if temp > 10 { 5 } else { 2 }; temp + bonus } else { let factor = x / 2; if factor > 3 { factor * 3 } else { factor + 1 } } } else { 0 }; println!("Result: {}", result); }
T/P/S - How would you rewrite this so it's easier to read?
One way: return early, like the percent example.
#![allow(unused)] fn main() { fn result_for(x: i32) -> i32 { if x <= 0 { return 0; } if x < 10 { let temp = x * x; let bonus = if temp > 10 { 5 } else { 2 }; return temp + bonus; } let factor = x / 2; if factor > 3 { factor * 3 } else { factor + 1 } } }
Another way: give each branch its own function, so the top-level function is just a short else if chain.
#![allow(unused)] fn main() { fn small_result(x: i32) -> i32 { let temp = x * x; let bonus = if temp > 10 { 5 } else { 2 }; temp + bonus } fn large_result(x: i32) -> i32 { let factor = x / 2; if factor > 3 { factor * 3 } else { factor + 1 } } fn result_for(x: i32) -> i32 { if x <= 0 { 0 } else if x < 10 { small_result(x) } else { large_result(x) } } }
Looping
In P1CP2 week you'll write programs that keep asking until they know something
In CP2, one person picks a secret number, and the other asks questions until they have it.
Every strategy you write for checkpoint 2 is a loop. Here's one that comes with the project:
/// Guess at random until the guess happens to be right.
pub fn random(keeper: &mut SecretKeeper, min: u32, max: u32) -> u32 {
loop {
let guess = random_range(min..max);
if keeper.ask_if_equal(guess) {
return guess;
}
}
}
loopruns forever, likewhile True:in Python- The only way out is to leave: here
returnends the whole function - Don't worry about
&mutyet.keeperis the one who knows the number and answers yes or no
The same loop, written another way
A loop is an expression, so it can hand back a value. break with a value leaves the loop and gives that value to whatever is waiting for it:
pub fn random(keeper: &mut SecretKeeper, min: u32, max: u32) -> u32 {
let answer = loop {
let guess = random_range(min..max);
if keeper.ask_if_equal(guess) {
break guess;
}
};
answer
}
returnleaves the whole functionbreakleaves just the loop, so it's handy when there's more to do after it
You can break out of for and while loops too, but without a value. Can you guess why?
for loops and ranges
A range is start..end, e.g. 1..5 or we can write (1..5)
The index will vary as:
Unless you use the notation (start..=end), in which case the index will vary as
Let's watch it in a for loop:
#![allow(unused)] fn main() { for i in (1..5) { println!("{}",i); }; }
Or inclusive:
#![allow(unused)] fn main() { // inclusive range for i in (1..=5) { println!("{}",i); }; }
Or you can get fancy:
#![allow(unused)] fn main() { // every other element for i in (1..5).step_by(2) { println!("{}",i); }; println!("And now for the reverse"); for i in (1..5).step_by(2).rev() { println!("{}",i) }; }
Try printing over your loop indices early on to make sure it's doing what you want it to do!
Arrays in Rust
- Arrays in Rust are of fixed length (we'll learn about more flexible
Veclater) - All elements of the same type (unlike tuples)
- You cannot add or remove elements from an array (but you can change their values)
- Arrays are 0-indexed and elements are
arr[i]
What will this return?
#![allow(unused)] fn main() { let mut arr = [1,7,2,5,2]; arr[1] = 13; println!("{} {}",arr[0],arr[1]); println!("{}",arr.len()); }
Three ways to loop over an array
#![allow(unused)] fn main() { let fruits = ["apple", "banana", "orange"]; // 1. Count through the positions for i in 0..fruits.len() { println!("fruits[{}] = {}", i, fruits[i]); } // 2. Take the values one at a time (`for fruit in fruits` works too) for fruit in fruits.iter() { println!("{}", fruit); } // 3. Get the position and the value together for (i, fruit) in fruits.iter().enumerate() { println!("fruits[{}] = {}", i, fruit); } }
| You need | Use |
|---|---|
| The position | for i in 0..fruits.len() |
| The value | for fruit in fruits.iter() or for fruit in fruits |
| Both | for (i, fruit) in fruits.iter().enumerate() |
| To change the elements | for i in 0..fruits.len(), then fruits[i] = ... |
Don't worry yet about what .iter() and .enumerate() are doing under the hood. For now, .iter() hands you the items one at a time, and .enumerate() pairs each one with its position as a tuple.
for fruit in fruits and for fruit in fruits.iter() do the same job for now. There is a difference, and we'll get to it when we learn about ownership.
You'll sometimes see &fruit written in that last loop. We'll get to what & means later.
Common array operations
#![allow(unused)] fn main() { // create array of given length and fill it with a specific value // note the semicolon vs the comma! let arr2 = [15;3]; for x in arr2 { print!("{} ",x); } println!(); }
#![allow(unused)] fn main() { // you can still infer or annotate types let arr2 : [u8;3] = [15;3]; }
Arrays come with useful built-in methods:
#![allow(unused)] fn main() { let mut scores = [85, 92, 78, 96, 88]; // Get the length println!("Number of scores: {}", scores.len()); // How to print an array println!("{:?}", scores); // There's also sort, min, clamp, truncate... you can look them up! }
Remember: {:?} is "debug" formatting
Let's pause here for some review (skip for time)
Take a minute with a partner to review functions from last lecture:
-
What's wrong with this function signature?
#![allow(unused)] fn main() { fn calculate_area(width, height) -> f64 { } -
What's wrong with this function?
#![allow(unused)] fn main() { fn mystery(x: i32) -> i32 { let result = x * 2; result + 1; } } -
What are two different ways you can fix this so it compiles?
fn main() { let x = 4; let y = 4.5; let z = x + y; println!("{}",z); }
while loops
While loops continue as long as a condition remains true (very similar to Python)
#![allow(unused)] fn main() { let mut number = 3; while number != 0 { println!("{number}!"); number -= 1; } println!("LIFTOFF!!!"); }
Using continue to jump to the next iteration
Think/pair/share - what is this going to print?
#![allow(unused)] fn main() { let mut x = 1; let result = loop { if x == 3 { x = x+1; continue; } println!("X is {}", x); x = x + 1; if x==6 { break x*2; } }; println!("Result is {}", result); }
FYI: you can label loops
break and continue apply to the innermost loop. A label like 'outer: lets you target an outer one instead:
#![allow(unused)] fn main() { 'outer: for x in 1..=4 { for y in 1..=3 { if x * y == 6 { break 'outer; // leaves both loops } } } }
You won't need this in this course. If you find yourself reaching for it, there is usually a clearer way to write the loop.
Which loop would you use?
T/P/S - Pick for, while, or loop for each of these games:
- Deal 5 cards to each of 4 players
- Roll a die until you get a 6
- Blackjack: keep drawing cards until your hand is 17 or over
- Hangman: keep taking guesses if you have lives left and the word isn't solved
for, twice: you know up front it's 4 players and 5 cardsloop, with abreakwhen you roll a 6. You can't know how many rolls it will takewhile hand < 17: one condition decides when to stopwhile lives > 0 && !solved: still one condition, built from two with&&
Aren't these all kind of the same?
#![allow(unused)] fn main() { for i in 0..3 { println!("{i}"); } }
How could you write this as a while loop? And that while as a loop?
#![allow(unused)] fn main() { let mut i = 0; while i < 3 { println!("{i}"); i += 1; } }
#![allow(unused)] fn main() { let mut i = 0; loop { if i >= 3 { break; } println!("{i}"); i += 1; } }
All three print 0 1 2.
Pick the one that's most concise and expresses what you mean:
for: "go through each of these"while: "keep going as long as this is true"loop: "keep going until something inside tells me to stop"
When for fits, it's the safest (there's no i += 1 to forget)
Activity time
Activity 8: loops, functions, and variables review
- Work alone or with one partner, and put both names on one sheet
- Paper only, no laptops
- Start with whatever part you feel least sure about
- We'll go over answers at the start of Wednesday's class
To think about til Wednesday: which one is faster?
Two ways to find the nth prime (the 4th prime is 7):
A. Check each number. Count up from 2. For each number, try dividing it by every smaller number. Stop once you've found n primes.
B. Cross out multiples. Write down every number up to 100,000. Cross out every multiple of 2, then every multiple of 3, then of the next number that isn't crossed out, and so on. Then count through what's left.
- How would you write each of these as loops?
- Which would you bet is faster?
- How could you find out for sure? How would you count the steps?
- Does the answer depend on
n?
That's where we start on Wednesday.
Lecture 9 - Complexity: how to compare two programs
Announcements
Learning objectives
By the end of today, you should be able to:
- Time two programs that do the same thing, and explain why debug and release give different numbers
- Count the steps in each part of a program, and say how that count grows with the input
- Use Big O notation to describe time and space complexity
- Recognize common complexity classes: O(1), O(log n), O(n), O(n^2), O(2^n)
- Apply key rules: drop constants, keep dominant terms
Part 1: Which one is faster?
Monday's question
Two ways to find the nth prime (the 4th prime is 7):
A. Check each number. Count up from 2. For each number, try dividing it by every smaller number. Stop once you've found n primes.
B. Cross out multiples. Write down every number up to 100,000. Cross out every multiple of 2, then every multiple of 3, then of the next number that isn't crossed out, and so on. Then count through what's left.
Which would you bet is faster? Does it depend on n?
The two programs in Rust
/// Count up from 2, checking each number, until we've found n primes.
fn nth_prime_a(n: u32) -> u32 {
let mut count = 0;
let mut candidate = 1;
while count < n {
candidate += 1;
let mut is_prime = true;
for d in 2..candidate {
if candidate % d == 0 {
is_prime = false;
break;
}
}
if is_prime {
count += 1;
}
}
candidate
}
/// Cross out every multiple of every number up to a limit,
/// then count through whatever is left.
fn nth_prime_b(n: u32) -> u32 {
let mut maybe_prime = [true; 100_000];
maybe_prime[0] = false;
maybe_prime[1] = false;
for i in 2..maybe_prime.len() {
if maybe_prime[i] {
let mut multiple = i * 2;
while multiple < maybe_prime.len() {
maybe_prime[multiple] = false;
multiple += i;
}
}
}
let mut count = 0;
for i in 0..maybe_prime.len() {
if maybe_prime[i] {
count += 1;
if count == n {
return i as u32;
}
}
}
0 // n was too big for this limit
}
Let's time them
cargo run
On my machine, in debug mode:
| n | nth prime | A | B |
|---|---|---|---|
| 4 | 7 | 709 ns | 2.4 ms |
| 100 | 541 | 0.2 ms | 2.8 ms |
| 1,000 | 7,919 | 25 ms | 2.3 ms |
| 2,000 | 17,389 | 87 ms | 1.4 ms |
| 4,000 | 37,813 | 343 ms | 1.7 ms |
| 8,000 | 81,799 | 1.5 s | 1.7 ms |
Now in release mode
cargo run --release
| n | A | B |
|---|---|---|
| 4 | 42 ns | 0.33 ms |
| 100 | 0.03 ms | 0.34 ms |
| 1,000 | 4.2 ms | 0.31 ms |
| 2,000 | 16 ms | 0.26 ms |
| 4,000 | 50 ms | 0.21 ms |
| 8,000 | 225 ms | 0.27 ms |
Time things in release mode. Debug is for building and fixing: it compiles fast and runs slow. Release takes longer to compile and runs about 6-7x faster here.
What just happened?
- A wins for small
n. B wins, by a lot, for bign - B takes about the same time no matter which prime you ask for
- Each time
ndoubles, A gets about 4x slower, not 2x
Our intuition says a job twice as big should take twice as long. It's often not that simple. It depends on the algorithm.
T/P/S - Why? Look at each loop in the code. What decides how many times it runs?
It's about more than getting the right answer
- A and B are both correct. Which one is better depends on how it gets used
- Ask an AI for "the nth prime" and you might get A
- Better asks:
- "Show me a few different approaches"
- "How does this scale as
ngrows?" - "I'll need lots of primes. Can we find them once and look them up after?"
- You can only ask those if you know they're the right questions
Counting the steps in each part
A has a loop inside a loop, and both grow with n:
- The
whileruns once per number checked, all the way up to thenth prime (81,799 forn= 8,000) - For each prime, the
fortries every smaller number
Double n and you check about twice as many numbers, each with about twice as many divisors to try: about 4x the work.
B never looks at n until the very end:
- Crossing out always covers all 100,000 numbers
- Counting through what's left is at most 100,000 more steps
So B does about the same work every time.
That's why it loses for the 4th prime and wins for the 8,000th.
Part 2: Big O notation - The math of "about how fast?"
Think-pair-share: Counting operations
Part 1: Given this code:
#![allow(unused)] fn main() { fn sum_to(n: u64) -> u64 { let mut total = 0; for i in 1..=n { total += i; } total } }
Question: How many addition operations happen?
Part 2: Now consider this code:
#![allow(unused)] fn main() { fn count_pairs(n: usize) -> usize { let mut count = 0; for i in 1..n { for _j in i..n { count += 1; } } count } }
Question: If we call count_pairs(n), how many times does the inner loop execute in total?
Can't figure out a formula? Try tracing it by hand with n = 3 or 4.
Part 1: n additions, one per time through the loop.
Part 2: For n = 4 the inner loop runs 3 + 2 + 1 = 6 times. In general (n-1) + (n-2) + ... + 1 = n(n-1)/2, which grows like n^2.
What is Big O?
Big O notation describes how runtime/memory grows as input size grows.
Key idea: We ignore:
- Exact number of operations
- Constants and performance on small inputs
- Hardware / OS dependent values
We focus on: The growth rate as n goes to infinity
So in Big O terms, B is the "constant" one, even though it lost for small n. Big O is about what happens as n gets big.
Example: Linear growth
#![allow(unused)] fn main() { fn print_up_to(n: u32) { for i in 0..n { // n iterations println!("{}", i); } } }
- n = 10: ~10 operations
- n = 100: ~100 operations
- Any n: ~n operations
This is O(n) - "linear time"
Example: Quadratic growth
#![allow(unused)] fn main() { fn print_all_pairs(n: u32) { for i in 0..n { // n iterations for j in 0..n { // n iterations for EACH i println!("{}, {}", i, j); } } } }
- n = 10: ~100 operations (10 × 10)
- n = 100: ~10,000 operations (100 × 100)
- Any n: ~n^2 operations
This is O(n^2) - "quadratic time"
Example: Exponential growth
A door opens for exactly one on/off setting of n light switches. Try them all:
#![allow(unused)] fn main() { fn try_every_setting(n: u32) -> u64 { let mut tried = 0; for _setting in 0..2u64.pow(n) { // the _ means we never use the variable tried += 1; } tried } }
- 10 switches: 1,024 settings (2^10)
- 20 switches: 1,048,576 settings (2^20)
- 40 switches: 1,099,511,627,776 settings (2^40)
Each extra switch doubles the work, like a population of bunnies doubling every generation.
This is O(2^n) - "exponential time" (explodes quickly!)
Example: Logarithmic growth
Now run the bunnies backwards. Start with 2, double every generation. How many generations until there are at least n?
#![allow(unused)] fn main() { fn generations_until(n: u64) -> u32 { let mut bunnies = 2; let mut generations = 0; while bunnies < n { bunnies *= 2; generations += 1; } generations } }
- 1,000 bunnies: 9 generations
- 1,000,000 bunnies: 19 generations
- 1,000,000,000 bunnies: 29 generations
Ask for 1,000x more bunnies and it only takes 10 more generations.
This is O(log n) - "logarithmic time" (very fast!)
Example: Constant time
#![allow(unused)] fn main() { fn last_digit(n: u64) -> u64 { n % 10 } }
- n = 10: 1 operation
- n = 1,000,000,000: 1 operation
- Any n: still 1 operation!
This is O(1) - "constant time" (doesn't depend on n)
Think about: What's the complexity?
#![allow(unused)] fn main() { fn evens_times_odds(n: u64) -> u64 { let mut evens = 0; for i in 0..n { if i % 2 == 0 { evens += 1; } } let mut odds = 0; for i in 0..n { if i % 2 == 1 { odds += 1; } } evens * odds } }
T/P/S - How does the work grow with n?
O(n). Two loops of n one after the other is 2n steps, and Big O drops the 2. A loop after a loop adds; a loop inside a loop multiplies.
Common complexity classes (from best to worst)
| Notation | Name | Example |
|---|---|---|
| O(1) | Constant | Array access by index |
| O(log n) | Logarithmic | Doubling until you reach n (the bunnies) |
| O(n) | Linear | Loop from 0 to n once |
| O(n log n) | Linearithmic | Good sorting algorithms |
| O(n^2) | Quadratic | Nested loops |
| O(2^n) | Exponential | Trying every on/off setting |
| O(n!) | Factorial | Trying all permutations |
Each step down this list is MUCH slower!
Rules for analyzing code
-
Loops: Multiply complexity by number of iterations
- Loop n times doing O(1) work = O(n)
- Loop n times doing O(n) work = O(n^2)
- Outer loop n times, inner loop m times = O(n m)
-
Drop constants and lower-order terms:
- O(3n) -> O(n)
- O(n^2 + n) -> O(n^2)
- O(5) -> O(1)
Let's do this one together
#![allow(unused)] fn main() { fn mystery_function(n: u64) -> u64 { let mut count = 0; for i in 0..n { count += i; } for _ in 0..10 { count += 1; } for i in 0..n { for j in 0..n { if i == j { count += 1; } } } count } }
n + 10 + n^2 steps. Drop the constant and the smaller term: O(n^2).
Space complexity exists too!
Big O also applies to memory usage. Back to the two prime finders:
- A keeps a few variables (
count,candidate,d) no matter how bigngets: O(1) space - B makes an array of 100,000
true/falsevalues before it does anything else. The memory it needs grows with its limit: O(limit) space
B buys its speed with memory. You make that trade all the time:
- Your browser caches websites. It keeps copies on disk, so a page you've visited loads without downloading it all again
- Looking for one thing in a box? Dump the whole box out on the floor. It takes up the whole floor, but now you can see everything at once
Best case vs. worst case vs. average case
Example: checking whether a single number is prime
#![allow(unused)] fn main() { fn is_prime(n: u64) -> bool { if n < 2 { return false; } for d in 2..n { if n % d == 0 { return false; } } true } }
- Best case: O(1) -
nis even, so it stops atd = 2 - Worst case: O(n) -
nis prime, so it tries everydfrom 2 to n - 1 - Average case: somewhere in between, and harder to work out
Usually we care most about worst case!
Sometimes the algorithm isn't even the whole story
Two ways to add up every number in a 10,000 by 10,000 grid:
// Across each row, then down to the next row
for r in 0..rows {
for c in 0..cols {
sum = sum + matrix[r][c];
}
}
// Down each column, then over to the next column
for c in 0..cols {
for r in 0..rows {
sum = sum + matrix[r][c];
}
}
Same 100 million additions. Same Big O. On my machine, going down the columns is about 6x slower (in release mode).
Why? We'll come back to that when we get to memory.
Activity Time
Complexity cheat sheet
Fast to Slow:
- O(1) - Instant, no matter the size
- O(log n) - Doubling the input adds one step
- O(n) - Proportional to size
- O(n log n) - The best we can do for sorting
- O(n^2) - Nested loops, gets bad quickly
- O(2^n) - Explodes! Avoid if possible
Lecture 10 - Sorting: complexity and recursion
Announcements
Learning objectives
By the end of today, you should be able to:
- Sort by hand with selection sort, insertion sort, and merge sort
- Find the Big O of selection and insertion sort from their loops
- Read and write a recursive function: a base case plus a smaller version of the same problem
- Explain why merge sort is O(n log n) from its call tree
- Explain why the fastest sort for a person is not always the fastest for a computer
Part 1: Sorting the way people do
How do you sort a hand of cards?
You're dealt 8 cards. Put them in order, smallest to largest.
What do you actually do?
Selection sort: find the smallest, move it to the front
/// Sort 8 cards smallest to largest. /// Find the smallest card left, swap it to the front, repeat. fn selection_sort(mut cards: [i32; 8]) -> [i32; 8] { for front in 0..cards.len() { // Find where the smallest card is, from `front` to the end let mut smallest = front; for check in (front + 1)..cards.len() { if cards[check] < cards[smallest] { smallest = check; } } // Swap the smallest card into the front spot let temp = cards[front]; cards[front] = cards[smallest]; cards[smallest] = temp; } cards } fn main() { println!("{:?}", selection_sort([60, 30, 80, 10, 50, 20, 70, 40])); }
A loop inside a loop: 7 + 6 + ... + 1 comparisons. O(n^2), like count_pairs on Wednesday.
Insertion sort: slide each card into place
/// Sort 8 cards smallest to largest. /// Keep the left side sorted. Slide each new card left until it fits. fn insertion_sort(mut cards: [i32; 8]) -> [i32; 8] { for next in 1..cards.len() { // Slide the card at `next` left while the card before it is bigger let mut spot = next; while spot > 0 && cards[spot - 1] > cards[spot] { let temp = cards[spot - 1]; cards[spot - 1] = cards[spot]; cards[spot] = temp; spot -= 1; } } cards } fn main() { println!("{:?}", insertion_sort([60, 30, 80, 10, 50, 20, 70, 40])); }
Also a loop inside a loop: O(n^2) in the worst case.
Think-pair-share: does the starting order matter?
- What if the cards are already sorted? How many comparisons does each sort make?
- What if they're in reverse order?
Selection sort doesn't care. Selection always scans everything that's left: 28 comparisons for 8 cards, regardless. O(n^2) best and worst.
Insertion sort does. Already sorted, each card checks its neighbor once and stops, so 7 comparisons, O(n) best case. Reversed, every card slides all the way left: 28 comparisons, O(n^2) worst case.
Part 2: Recursion
What if you split the pile?
Sorting 16 cards alone is a lot of comparisons.
- Split the pile in half and hand each half to a friend
- Each friend splits their half and hands it off too
- ...until everyone holds one card, which is already sorted
Every friend is doing the same job on a smaller pile.
A function that calls itself on a smaller version of the problem is recursive.
A recursive function you already know
Wednesday's sum_to, with a loop:
#![allow(unused)] fn main() { fn sum_to(n: u64) -> u64 { let mut total = 0; for i in 1..=n { total += i; } total } }
The same thing, with no loop:
fn sum_to(n: u64) -> u64 { if n == 0 { return 0; // base case: nothing left to add } n + sum_to(n - 1) // a smaller version of the same problem } fn main() { println!("{}", sum_to(3)); }
Tracing sum_to(3)
#![allow(unused)] fn main() { fn sum_to(n: u64) -> u64 { if n == 0 { return 0; } n + sum_to(n - 1) } }
What happens when we call sum_to(3)?
sum_to(3) = 3 + sum_to(2)
= 2 + sum_to(1)
= 1 + sum_to(0)
= 0 base case, start returning
= 1 + 0 = 1
= 2 + 1 = 3
= 3 + 3 = 6
Each call waits for the one below it to answer. Nothing adds up until the base case returns.
Every recursive function has two parts
- A base case: a problem small enough to answer right away
- A recursive step: call yourself on a problem that is smaller, closer to the base case
Write the base case first. Then ask: does every call get closer to it?
Think-pair-share: fill in the blanks
Wednesday's mystery function counted the digits in a number with a loop. Write it recursively:
/// Count the digits in n. count_digits(4096) is 4.
fn count_digits(n: u64) -> u64 {
if n < 10 {
return ___;
}
___ + count_digits(___)
}
/// Count the digits in n. count_digits(4096) is 4. fn count_digits(n: u64) -> u64 { if n < 10 { return 1; // one digit left } 1 + count_digits(n / 10) // this digit, plus the digits after chopping it off } fn main() { println!("{}", count_digits(4096)); }
What if there's no base case?
#![allow(unused)] fn main() { fn count_digits(n: u64) -> u64 { 1 + count_digits(n / 10) } count_digits(115); }
Part 3: Merge sort
Merging two sorted piles
Two piles, each already sorted, smallest on top:
Left: 20 50 80 Right: 10 30 90
Look at only the two top cards. Take the smaller one. Repeat.
20 vs 10 take 10 10
20 vs 30 take 20 10 20
50 vs 30 take 30 10 20 30
50 vs 90 take 50 10 20 30 50
80 vs 90 take 80 10 20 30 50 80
right pile left: 10 20 30 50 80 90
At most one comparison per card placed: merging is O(n).
Merge sort
To sort a pile:
- Base case: one card? It's sorted. Done
- Split the pile in half
- Merge sort each half (recursion!)
- Merge the two sorted halves
[60, 30, 80, 10, 50, 20, 70, 40] split
[60, 30, 80, 10] [50, 20, 70, 40] split
[60, 30] [80, 10] [50, 20] [70, 40] split
[60] [30] [80] [10] [50] [20] [70] [40] base case: one card each
[30, 60] [10, 80] [20, 50] [40, 70] merge
[10, 30, 60, 80] [20, 40, 50, 70] merge
[10, 20, 30, 40, 50, 60, 70, 80] merge
Why O(n log n)?
[10, 20, 30, 40, 50, 60, 70, 80] merging this level touches 8 cards
[10, 30, 60, 80] [20, 40, 50, 70] 8 cards
[30, 60] [10, 80] [20, 50] [40, 70] 8 cards
- Work per level: every card gets merged once, so about
n - Number of levels: halve 8 until you reach 1 card: 8, 4, 2, 1, so 3 levels so log n
n work on each of log n levels: O(n log n)
The picture of calls splitting into two smaller calls is a tree. You'll see a lot more of these.
Don't just memorize "merge sort is n log n." Draw the tree and count: how much work per level, times how many levels.
How much faster is that?
Comparisons for our 8 and 16 card starting orders (activity!):
| Cards | Selection | Insertion | Merge |
|---|---|---|---|
| 8 | 28 | 20 | 17 |
| 16 | 120 | 75 | 49 |
| 1,000,000 | about 500 billion | about 250 billion | about 20 million |
Double the cards: selection does about 4x the comparisons. Merge does about 3x, and the gap keeps growing.
Quicksort and .sort()
Quicksort is another split-the-pile recursive sort. Pick one card, put smaller cards on its left and bigger on its right, then quicksort each side.
.sort(): in Rust you almost never write your own sort, you just:
fn main() { let mut cards = [60, 30, 80, 10, 50, 20, 70, 40]; cards.sort(); println!("{:?}", cards); }
.sort()is built on merge sort, and switches to insertion sort for 20 items or fewer.sort_unstable()is built on quicksort
Watch them sort
15 Sorting Algorithms in 6 Minutes
Watch for selection, insertion, merge, and quick. What shape does each one make as it works? For the ones we haven't talked about - can you guess what they do? (Heap sort, Radix sort, etc.)
Just for fun: in the order the video shows them, what do you think each one does?
| Sort | Your guess |
|---|---|
| Selection sort | We did this one |
| Insertion sort | We did this one |
| Quick sort | We did this one |
| Merge sort | We did this one |
| Heap sort | |
| Radix sort (LSD) | |
| Radix sort (MSD) | |
| std::sort | |
| std::stable_sort | |
| Shell sort | |
| Bubble sort | |
| Cocktail shaker sort | |
| Gnome sort | |
| Bitonic sort | |
| Bogo sort |
Activity 10: Sorting race
- Groups of 5-6 (6 groups) - each get 4 packets
- Four people race at once, one each: insertion, selection, merge, and freestyle (your own strategy)
- Person 5 is the timer and fills in the Google Form. Person 6, if you have one, checks
- Same starting order for everyone. Round 1 with 8 cards, round 2 with 16
- Swap roles between rounds
Before each round: which sort will win?
Results
- Did the winner match the comparison counts?
- Which sort was easier for people than for a computer? Why?
- Did anything change between 8 and 16 cards? What about 1,000?
- Why would Rust's
.sort()use insertion sort for small lists?
Appendix: merge sort in Rust
Just FYI if you're curious. Vec is a list that can grow, and &cards[..mid] means "a glance at the first half of cards". Both are coming later. Can you find the base case and the two recursive calls?
/// Merge two sorted piles into one sorted pile. fn merge(left: &[i32], right: &[i32]) -> Vec<i32> { let mut result = Vec::new(); let mut l = 0; // position in the left pile let mut r = 0; // position in the right pile while l < left.len() && r < right.len() { if left[l] <= right[r] { result.push(left[l]); l += 1; } else { result.push(right[r]); r += 1; } } // Once one pile is empty while l < left.len() { result.push(left[l]); l += 1; } while r < right.len() { result.push(right[r]); r += 1; } result } fn merge_sort(cards: &[i32]) -> Vec<i32> { if cards.len() <= 1 { return cards.to_vec(); } let mid = cards.len() / 2; let left = merge_sort(&cards[..mid]); let right = merge_sort(&cards[mid..]); merge(&left, &right) } fn main() { println!("{:?}", merge_sort(&[60, 30, 80, 10, 50, 20, 70, 40])); }
Lecture 11 - Structs: bundling data and giving it methods
Announcements
Learning objectives
By the end of today, you should be able to:
- Define a struct to group related data under one name
- Use a tuple struct when the fields don't need names
- Write methods in an
implblock, and call them with a dot - Choose between
&selfand&mut self, and say whatselfalone would do - Write a constructor and explain why it uses
::instead of. - Say what
pubdoes to a field, and why you would leave it off - Use a
Vecas a list that can grow
Part 1: You've already been using one
Three weeks of keeper.something()
From Project 1:
let mut keeper = dealer.deal();
if keeper.ask_if_greater(50) {
// the secret is bigger than 50
}
println!("Questions asked: {}", keeper.questions_asked());
keeper is not an i32, a bool, or an array. It is a custom type we wrote.
What secret_keeper.rs actually says
Abridged a little, but this is the shape of it:
struct SecretKeeper { secret: u32, questions: u32, } impl SecretKeeper { fn questions_asked(&self) -> u32 { self.questions } fn ask_if_greater(&mut self, guess: u32) -> bool { self.questions += 1; guess < self.secret } } fn main() { let mut keeper = SecretKeeper { secret: 42, questions: 0 }; println!("{}", keeper.ask_if_greater(50)); println!("Questions asked: {}", keeper.questions_asked()); }
Two halves:
struct: the data it holdsimpl: what you can ask it to do
The problem structs solve
Say you're tracking a customer. You could use loose variables:
let customer_name = "Alice Smith";
let customer_age = 25;
let customer_state = "NY";
let customer_member = true;
This works, but it's not ideal.
What sucks about this?
Three things wrong with loose variables
let customer_name = "Alice Smith";
let customer_age = 25;
let customer_state = "NY";
let customer_member = true;
Nothing holds them together. You'd need to pass them as four arguments into a function, and the compiler might not notice if you mix them up.
A second customer is a mess. 4 more vars, nothing linking Alice's name to Alice's age.
The logic lives somewhere else. (We'll see more of that in a minute)
Group them into one type
#![allow(dead_code)] struct Customer { name: String, age: u32, state: String, member: bool, } fn main() { let alice = Customer { name: "Alice Smith".to_string(), age: 25, state: "NY".to_string(), member: true, }; println!("{} is {}", alice.name, alice.age); }
struct Customer { ... }defines a new type, once- The block with the values makes one of them
- Access a field with a dot:
alice.age(like tuple notation!)
The loose version said "NY" (&str) but the field needs "NY".to_string()(String) because the compiler wants to know where the text lives and for how long. Like before... more info later in the term.
Changing fields and printing
#![allow(dead_code)] #[derive(Debug)] struct Customer { name: String, age: u32, state: String, member: bool, } fn main() { let mut alice = Customer { name: "Alice Smith".to_string(), age: 25, state: "NY".to_string(), member: true, }; alice.age = 26; // needs `mut` on alice println!("{:?}", alice); }
mutis on the whole struct, not on one field. Either all of it can change or none of it can#[derive(Debug)]gives you{:?}, the same one you used for arrays
Tuple structs: when we don't need field names
#![allow(dead_code)] #[derive(Debug)] struct Point3D(f64, f64, f64); #[derive(Debug)] struct BoxOfDonuts(u32); fn main() { let corner = Point3D(3.0, 4.0, 5.0); let dozen = BoxOfDonuts(12); println!("x is {}, y is {}", corner.0, corner.1); println!("{:?}", dozen); }
Fields by position, not by name.
BoxOfDonuts(12) is not a u32, so you can't hand it to a function expecting a count of something else. That's the point of it.
Part 2: Methods
Functions that belong to a type
Without methods, every function takes the struct as an argument:
fn area(rect: &Rectangle) -> f64 { ... }
fn perimeter(rect: &Rectangle) -> f64 { ... }
let a = area(&rect);
With an impl block, they hang off the type itself:
impl Rectangle {
fn area(&self) -> f64 { ... }
fn perimeter(&self) -> f64 { ... }
}
let a = rect.area();
The difference is that now they travel with the type, and you find them by typing rect.
What that buys you: adding a shape
Say a circle turns up. With one function for everything, you need a way to tell the shapes apart, and every shape's fields end up on one struct:
struct Shape {
kind: String,
width: f64,
height: f64,
radius: f64, // meaningless unless kind is "circle"
}
fn area(shape: &Shape) -> f64 {
if shape.kind == "rectangle" {
shape.width * shape.height
} else if shape.kind == "circle" {
3.14159 * shape.radius * shape.radius
} else {
0.0 // and now what?
}
}
A triangle adds a field nobody else uses, and it edits area, and perimeter, and everything else that branches on kind. Nothing stops you writing Shape { kind: "circle", width: 10.0, radius: 0.0 } either.
The way out of that is one function per shape:
fn area_rectangle(r: &Rectangle) -> f64 { ... }
fn area_circle(c: &Circle) -> f64 { ... }
fn perimeter_rectangle(r: &Rectangle) -> f64 { ... }
fn perimeter_circle(c: &Circle) -> f64 { ... }
Now the compiler checks the types for you, but you are the one keeping the names straight, and the triangle is two more functions.
With methods, they can all just be called area:
struct Rectangle { width: f64, height: f64 } struct Circle { radius: f64 } impl Rectangle { fn area(&self) -> f64 { self.width * self.height } } impl Circle { fn area(&self) -> f64 { 3.14159 * self.radius * self.radius } } fn main() { let rect = Rectangle { width: 10.0, height: 5.0 }; let circle = Circle { radius: 3.0 }; println!("{:.2} {:.2}", rect.area(), circle.area()); }
Two types, same method name, and no clash: rect. can only reach Rectangle's. The triangle is one new struct and one new impl, and no other code needs to change.
&self: the method just reads
struct Rectangle { width: f64, height: f64, } impl Rectangle { fn area(&self) -> f64 { self.width * self.height } } fn main() { let rect = Rectangle { width: 10.0, height: 5.0 }; println!("{}", rect.area()); // like calling area(&rect) println!("{}", rect.width); // rect is still fine }
selfis the value you called the method on. Here,rect- The
&means the method borrows it: a look, not a handover - Most methods are
&self
&mut self: the method changes something
struct Rectangle { width: f64, height: f64, } impl Rectangle { fn scale(&mut self, factor: f64) { self.width *= factor; self.height *= factor; } } fn main() { let mut rect = Rectangle { width: 10.0, height: 5.0 }; rect.scale(2.0); println!("{} by {}", rect.width, rect.height); // 20 by 10 }
&mut selfmeans the method may change the fields- The variable has to be
mut, or the call won't compile - That's why
keeperhad to bemutin Project 1:ask_if_greatercounts the question
There is a third one, but you don't want it yet
impl Rectangle {
fn into_area(self) -> f64 { // no &
self.width * self.height
}
}
Plain self takes the whole struct with it. After you call the method, the variable is gone, and using it again is a compile error.
Useful for turning one thing into another. Rare. For now, write &self or &mut self.
Which one do I write?
| Parameter | The method... | After the call |
|---|---|---|
&self | reads the fields | the value is still yours |
&mut self | changes the fields | the value is still yours, and changed |
Plain self is the third option: the value is consumed, and you'll rarely write it this term.
Start with &self. Reach for &mut self only when the method actually changes a field. If the compiler wants more, it will say so.
Think-pair-share: &self or &mut self?
You're writing a Playlist. Which does each method take?
total_minutes, adds up the length of every songadd_song, puts one more song on the endis_empty, says whether there are any songsrename, gives the playlist a new title
&self, reading&mut self, changing&self, reading&mut self, changing
The question is always the same one: does this change a field?
Constructors: building one without spelling it out
#![allow(dead_code)] #[derive(Debug)] struct Rectangle { width: f64, height: f64, } impl Rectangle { fn new(width: f64, height: f64) -> Rectangle { Rectangle { width, height } // short for width: width, height: height } fn square(side: f64) -> Rectangle { Rectangle { width: side, height: side } } } fn main() { let rect = Rectangle::new(10.0, 5.0); let unit = Rectangle::square(1.0); println!("{:?} {:?}", rect, unit); }
No self parameter, because there's nothing to call it on yet. You're making the thing.
So it's Rectangle::new(...) with two colons, not rect.new(...) with a dot.
A dot means "I already have one of these." Two colons means "make me one" or "this belongs to the type, not to a value."
new is not a keyword. It's a convention, and a strong one, but nothing special happens when you use the name. Rectangle::square is a constructor too.
Vec: an array that can grow
An array is a fixed size forever. A Vec is a list that grows:
fn main() { let mut grades = Vec::new(); // the same :: you just saw grades.push(85.0); grades.push(92.0); println!("{} grades", grades.len()); println!("first is {}", grades[0]); // index it like an array println!("{:?}", grades); }
Vec is a struct with methods, exactly like the ones you're writing today.
How it manages memory is a later lecture, and in Project 2 you'll build your own.
let grades = Vec::new(); on its own gives you "type annotations needed". Rust works out what the Vec holds from the first thing you push, so it needs to see one.
You've been calling methods for weeks
cards.sort(); // Friday
scores.iter(); // Activity 8
name.len();
text.to_string();
Every one of those is a method on a type someone else wrote:
| What you wrote | What it really is | Which self |
|---|---|---|
cards.sort() | sort(&mut cards) | &mut self, it reorders the cards |
name.len() | len(&name) | &self, just reading |
Vec::new() | nothing to call it on | no self at all |
Method or plain function?
A method goes on the type when it needs the data inside it.
impl Customer {
fn is_adult(&self) -> bool { self.age >= 18 } // needs the customer
}
fn tax_rate(state: &str) -> f64 { ... } // doesn't
fn average_age(customers: &Vec<Customer>) -> f64 { ... } // needs multiple
When writing a struct, ask yourself "what would someone expect this type to have and do?"
Naming for structs and methods
- Types are
CamelCase, fields and methods aresnake_case - Don't repeat the type inside it.
Customer { name, age }, notCustomer { customer_name, customer_age } is_andhas_for methods that answer yes or no- A field called
datatells the next reader nothing - Rust style avoids "get_" for access (
customer.age()notcustomer.get_age())
The other reason: there is only one place to get it wrong
Say a BankAccount must never go negative, and other functions want to withdraw from it.
If you let them reach in, this has to be written every time:
if amount > account.balance {
println!("not enough funds");
}
account.balance -= amount;
Put it in a method, and there is exactly one:
impl BankAccount {
fn withdraw(&mut self, amount: i32) {
if amount > self.balance {
println!("not enough funds");
}
self.balance -= amount;
}
}
Same code, but the difference is how many places you need to keep in sync.
So what stops you reaching in anyway?
You have written this:
println!("Questions asked: {}", keeper.questions_asked());
SecretKeeper has a field called questions. Why did you call a method instead of just writing keeper.questions?
Because you are not allowed to
println!("{}", keeper.questions);
error[E0616]: field `questions` of struct `SecretKeeper` is private
--> src/main.rs:7:22
|
7 | println!("{}", keeper.questions);
| ^^^^^^^^^ private field
In secret_keeper.rs:
pub struct SecretKeeper {
source: Source,
questions: u32,
already_used: Vec<u32>,
}
impl SecretKeeper {
pub fn questions_asked(&self) -> u32 {
self.questions
}
}
pub means other files can see this. The struct is pub, and so is the method. The fields are not.
So from your code you can ask how many questions you have asked. You cannot set the counter to zero.
Let's build one together: a grade tracker
struct Student { name: String, grades: Vec<f64>, } impl Student { fn new(name: String) -> Student { Student { name, grades: Vec::new(), } } fn add_grade(&mut self, grade: f64) { self.grades.push(grade); } fn average(&self) -> f64 { if self.grades.len() == 0 { return 0.0; } let mut total = 0.0; for grade in &self.grades { total += grade; } total / self.grades.len() as f64 } } fn main() { let mut alice = Student::new("Alice".to_string()); alice.add_grade(85.0); alice.add_grade(92.0); println!("{}'s average: {:.1}", alice.name, alice.average()); }
Activity Time
See Activity 11
Lecture 12 - Enums: variants, match, and exhaustiveness
Announcements
Learning objectives
By the end of today, you should be able to:
- Define an enum, including variants that carry data
- Use
#[derive(Debug)]and#[derive(PartialEq)]to print and compare them - Write a
matchthat covers every variant, and say what the compiler does when you miss one - Choose between an enum and a struct for a piece of data
- Read a pattern guard, an
ifon amatcharm - Use
Option<T>when you want to return a value or nothing
Monday's Customer wasn't perfect
struct Customer {
name: String,
age: u32,
state: String,
member: bool,
}
name is free text. Whatever a person types is a legal name, and no rule we could write would say otherwise.
state is not free text. There are fifty of them, more or less.
But String lets us write both fields the same way.
What does Alice pay?
#[derive(Debug)] struct Customer { name: String, age: u32, state: String, member: bool, } fn shipping_cost(c: &Customer) -> f64 { if c.state == "NY" { 5.00 } else { 12.00 } } fn main() { let alice = Customer { name: "Alice Smith".to_string(), age: 25, state: "ny".to_string(), member: true, }; println!("{} pays ${:.2}", alice.name, shipping_cost(&alice)); }
Spellings the compiler is happy with
state: "ny".to_string()
state: "New York".to_string()
state: "NY ".to_string()
state: "Nueva York".to_string()
They all compile, but only one matches the shipping_cost function.
Our mistake was that state isn't a free string, it's more like a dropdown menu.
A text box, or a dropdown
A text box accepts the typo. A dropdown does not offer it.
Rust lets you build the dropdown, as a type:
enum State {
NY,
MA,
CA,
// ... 47(ish) more
}
struct Customer {
name: String,
age: u32,
state: State, // not String
member: bool,
}
The field no longer accepts text. It accepts one of the variants of State, and nothing else.
The typo is now a compile error
let alice = Customer {
name: "Alice Smith".to_string(),
age: 25,
state: State::ny, // won't compile
member: true,
};
error[E0599]: no variant, associated function, or constant named `ny`
found for enum `State` in the current scope
help: there is a variant with a similar name
|
18 - state: State::ny,
18 + state: State::NY,
This is a good thing! We catch the issue early and don't accidentally charge the wrong thing.
So what is an Enum anyway?
enum is short for "enumeration" and allows you to define a type by enumerating its possible variants.
Let's make another one:
#![allow(unused)] fn main() { // define the enum and its variants enum Direction { North, East, South, West, SouthWest, } // create instances of the enum variants let dir_1 = Direction::North; // dir is inferred to be of type Direction let dir_2: Direction = Direction::South; // dir_2 is explicitly of type Direction }
The enum declaration is defining our new type, so now a type called Direction exists, alongside i32, f64, bool, etc.
The let declarations are creating instances of the Direction type.
Using "use" as a shortcut
enum Direction {
North,
East,
South,
West,
SouthWest,
}
// Bring the variant `East` into scope
use Direction::East;
// Bring two of them into scope
use Direction::{South, West};
// Bring all of them into scope
use Direction::*;
// we didn't have to specify "Direction::"
let dir_3 = East;
let dir_4 = North;
Teaching Rust two things about your enum
Out of the box, Rust will not print your enum and will not compare two of them. But you can insist.
// #[derive(Debug, PartialEq)] enum Direction { North, East, South, West, } use Direction::*; fn main(){ let here = North; let there = South; println!("{:?}", here); println!("{}", here == there); }
Debugis what{:?}needsPartialEqis what==and!=need
Control Flow with match
The match statement is used to control flow based on the value of an enum.
enum Direction { North, East, South, West, } use Direction::*; fn report(dir: Direction) { match dir { North => println!("N"), South => println!("S"), West => { // can do more than one thing println!("Go west!"); println!("W") } East => println!("E"), }; } fn main() { report(North); report(East); report(South); report(West); }
dir is a parameter typed Direction, so the only things it can be are the four variants.
If we tried doing this with if/else statements it would have to look like:
// The ugly if/else version (and it needs the PartialEq derive):
if dir == North {
println!("N");
} else if dir == East {
println!("E");
} else if dir == South {
println!("S");
} else if dir == West {
println!("Go west!");
println!("W");
} else {
// Nothing here should ever run, but the compiler can't tell us that,
// and it can't tell us if we forget one either
unreachable!();
}
Covering all variants with match
match is exhaustive, so we must cover all the variants!
If we didn't...
enum Direction { North, East, South, West, } use Direction::*; fn main() { let dir_2: Direction = South; match dir_2 { North => println!("N"), South => println!("S"), // East and West not covered }; }
But there is a way to match anything left.
enum Direction { North, East, South, West, } use Direction::*; fn main() { let dir_2: Direction = Direction::North; match dir_2 { North => println!("N"), South => println!("S"), // match anything left _ => (), // covers all the other variants and doesn't do anything } }
WARNING - your catch-all has to go last or it'll gobble everything up!
Just like if-elseif-else... or a series of filters.
enum Direction { North, East, South, West, } use Direction::*; fn report(dir: Direction) { match dir { _ => println!("anything else"), // will never get here!! North => println!("N"), South => println!("S"), } } fn main() { report(North); report(East); report(South); report(West); }
Every call prints anything else, not what you want. The warning helps here!
warning: unreachable pattern
|
10 | _ => println!("anything else"),
| - matches any value
13 | North => println!("N"),
| ^^^^^ no value can reach this
Another quick example
enum Coin { Penny, Nickel, Dime } fn value(c: Coin) -> u32 { match c { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, } } fn main() { println!("{}", value(Coin::Penny)); println!("{}", value(Coin::Dime)); }
Putting Data in an Enum Variant
Each variant can come with additional information
#[derive(Debug)] enum DivisionResult { Answer(u32), DivisionByZero, } fn divide(x:u32, y:u32) -> DivisionResult { if y == 0 { return DivisionResult::DivisionByZero; } else { return DivisionResult::Answer(x / y); } } fn main() { // each pass through the loop destructures one pair into a and b for (a,b) in [(9,3), (7,0)] { match divide(a,b) { DivisionResult::Answer(result) // assigns the variant value to result => println!("This result is {}",result), DivisionResult::DivisionByZero => println!("noooooo!!!!"), }; } }
This result is 3
noooooo!!!!
So which one?
A struct has several parts, all at once.
An enum is one of a few alternatives.
| Reach for an enum when | Reach for a struct when |
|---|---|
| The value is one of a few alternatives | The value has several parts, all at once |
| The cases carry different data, or none | Every one of them carries the same fields |
| You want the compiler to make you handle each case | You want to add a field later without touching every match |
Real code usually has both: a struct to group the fields, and an enum for the field that is one of a few choices.
Sometimes either one will work and you pick the one that fits better, sometimes you're forced into one.
The same type, written both ways
| As a struct | As an enum | |
|---|---|---|
| Temperature prefer struct |
|
|
Beyond enums: match works on other types
Matching on a condition, which you will see again in a minute:
fn main() { let number = 42; match number { x if x % 2 == 0 => println!("{} is even", x), x => println!("{} is odd", x), } }
The if on an arm is a guard. That arm matches only when the pattern fits and the condition holds.
Other shapes, one line each. Full versions are on the website:
(0, y) => ... // a tuple, keeping y
13..=19 => ... // a range
[1, _, _] => ... // an array starting with 1
Book { rating, .. } => ... // a struct, keeping one field
The Option Enum
Find someone's last name
We've all written something like this in Python:
def find_index(target, names):
for i in range(len(names)):
if target == names[i]:
return i
return -1
index = find_index("Kesar", names)
print(last_names[index])
Now let's look up somebody who is not in the list
index = find_index("Totoro", names) # Totoro is not in names
print(last_names[index]) # last_names[-1]
No error. No crash. It prints... what?
How Rust solves it elegantly
There is a built-in enum Option<T> with two variants:
Some(T)- The variantSomecontains a value of typeTNone
Useful for when there may be no output
- Like
Noneornullin other languages - Rust makes you explicitly handle them, preventing bugs that are extremely common in other languages
- This might look a little like "optional" parameters in python (
def myfn(arg: Optional[int] = None):but functions differently)
You write Direction::North with the enum's name in front, but plain Some and None with nothing in front. They are in the prelude, the short list of names Rust hands you for free in every file. Option::Some(3) works too, and nobody writes it.
An Option<T> example
Here is prime-finding code whose return type is Option<u32>.
If it finds a prime, it returns Some(u32) holding that prime.
If it does not, it returns None.
fn is_prime(x:u32) -> bool { if x <= 1 { return false;} for i in 2..=((x as f64).sqrt() as u32) { if x % i == 0 { return false; } } true } fn prime_in_range(a:u32,b:u32) -> Option<u32> { // returns an Option<u32> for i in a..=b { if is_prime(i) {return Some(i);} } None } fn main(){ let tmp : Option<u32> = prime_in_range(90,906); // let tmp : Option<u32> = prime_in_range(20,22); println!("{:?}",tmp); }
Extracting the contents of an Option<T> with match
fn main() { let tmp : Option<u32> = Some(3); // let tmp: Option<u32> = None; match tmp { Some(____) => println!("Got: {}",____), None => println!("None"), }; }
How we do find_index, in Rust
fn find_index(target: &str, names: [&str; 3]) -> Option<usize> { for i in 0..names.len() { if target == names[i] { return Some(i); } } None } fn main() { let names = ["Kesar", "Mei", "Satsuki"]; let last_names = ["Patel", "Kusakabe", "Kusakabe"]; for target in ["Kesar", "Totoro"] { match find_index(target, names) { Some(i) => println!("{} {}", target, last_names[i]), None => println!("{} is not in the list", target), } } }
Kesar Patel
Totoro is not in the list
There is no -1 to index with by accident. To get the number out you have to go through the match, and the match makes you say what happens when it is None.
The name on the left is one you make up
Same function, different names, same output:
fn main() { let number = 42; match number { tuesday if tuesday % 2 == 0 => println!("{} is even", tuesday), y => println!("{} is odd", y), } }
x, y, tuesday. Rust knows none of these names before you write them. A pattern on the left of => creates a new variable, and it exists only inside that one arm. (You can even call it number again but that's confusing)
Same thing in Some(x). The x catches whatever was inside the Some.
let tmp: Option<u32> = Some(3);
match tmp {
Some(x) => println!("{}", x), // 3
None => println!("nothing"),
}
Activity Time
Paper instructions, Playground for solving, Gradescope for submitting.
Lean on the compiler! (And lecture notes.)
Feel free to change the problems so they ask you to PRINT strings instead of return them.
These problems are harder than what we'd expect you to hand-code!
More match, on the website
Everything past this point is on the lecture page rather than on your paper. Six short appendices, if you want to go further:
- Matching on a struct, and guarding an arm with
if if let, a shorthand for when you only care about one arm of amatchmatchas an expression, so an arm's value goes straight into alet- The other pattern shapes: tuples, ranges, and arrays
- More destructuring: partial with
.., and a pattern in a function parameter - Two more enums: the temperature types with their methods, and Project 1's
SecretKeeper
Matching on a struct, and guarding an arm
match works on structs too. Name the fields you want, .. for the rest.
#![allow(unused)] fn main() { #[derive(Debug)] struct Book { title: String, rating: f64, pages: u32, } fn get_rating(book: &Book) -> f64 { match book { &Book { rating, .. } => rating, } } fn classify(book: &Book) -> &str { match book { &Book { rating, pages, .. } if rating >= 4.5 && pages >= 400 => "Epic Bestseller", &Book { rating, .. } if rating >= 4.5 => "Highly Rated", _ => "Standard", } } }
Arms are tried top to bottom, so the fussiest guard goes first.
The & in &Book { rating, .. } is there because book is a &Book. The pattern is shaped like the type it matches. (And we'll understand exactly how it works... you guessed it, after the midterm.)
Bonus - Simplified matching with if let (FYI)
When you care about one case only, match makes you write a _ arm you have no use for:
enum Direction { North, East, South, West, } use Direction::*; fn main() { for dir in [North, East, South, West] { match dir { North => println!("this one is North"), _ => (), }; } }
That happens often enough to have a shorthand:
enum Direction { North, East, South, West, } use Direction::*; fn main() { for dir in [North, East, South, West] { if let North = dir { // YES THIS LOOKS BACKWARDS! It's more like match than if println!("this one is North"); } } }
You can add an else, the same as on a regular if.
You will meet it most often on Option, where the pattern carries a value. These two do the same thing:
fn main() { let tmp: Option<u32> = Some(3); // with match match tmp { Some(x) => println!("match: {}", x), None => println!("nothing"), } // with if let, when you only care about one of the two cases if let Some(x) = tmp { println!("if let: {}", x); } }
if let reads backwards the first few times. Some(x) is the pattern and tmp is the
value being tested against it, which is the same order a match arm uses. And unlike ==,
it can reach inside a variant and pull the value out.
Appendix: match as an expression (FYI)
The result of a match can be used as an expression.
Each branch (arm) returns a value.
#[derive(Debug)] enum Direction { North, East, South, West, } use Direction::*; fn main() { // turn left let dir_facing = North; println!("{:?}", dir_facing); let after_turning_left = match dir_facing { North => West, West => South, South => East, East => North }; println!("{:?}", after_turning_left); }
Appendix: the other pattern shapes (FYI)
Matching tuples:
fn main() { let point = (3, 5); match point { (0, 0) => println!("Origin"), (0, y) => println!("On Y-axis at {}", y), (x, 0) => println!("On X-axis at {}", x), (x, y) => println!("Point at ({}, {})", x, y), } }
Matching ranges:
fn main() { let age: u32 = 25; match age { 0..=12 => println!("Child"), 13..=19 => println!("Teenager"), 20..=64 => println!("Adult"), 65.. => println!("Senior"), } }
Destructuring arrays:
fn main() { let arr = [1, 2, 3]; match arr { [1, 2, 3] => println!("Exact match"), [1, _, _] => println!("Starts with 1"), [_, _, 3] => println!("Ends with 3"), _ => println!("Something else"), } }
Appendix: more destructuring (FYI)
You have done this with tuples: let (x, y) = (3, 5);. A struct works the same way, naming every
field: let Book { title, rating, pages } = dune;.
Partial destructuring with .., when you only want some of the fields:
struct Book { title: String, rating: f64, pages: u32 } fn main() { let dune = Book { title: String::from("Dune"), rating: 4.6, pages: 412 }; println!("rating: {}", dune.rating); // ignore rating this time let Book { title, pages, .. } = dune; println!("{} is {} pages", title, pages); }
In a function parameter, so the body never mentions the struct at all:
fn print_pages(Book { title, pages, .. }: &Book) {
println!("{} is {} pages", title, pages);
}
Appendix: the temperature types, and Project 1's SecretKeeper (FYI)
The two temperature types from the slide, with a sensor id added and the methods that use them. Both versions print identical output.
Temperature as a struct. Converting needs the scale; reading the sensor id does not.
enum Scale { Fahrenheit, Celsius } struct Temperature { degrees: f64, scale: Scale, sensor_id: u32, } impl Temperature { // converting needs the scale fn in_celsius(&self) -> f64 { match self.scale { Scale::Celsius => self.degrees, Scale::Fahrenheit => (self.degrees - 32.0) * 5.0 / 9.0, } } } fn main() { let body = Temperature { degrees: 98.6, scale: Scale::Fahrenheit, sensor_id: 7 }; let boiling = Temperature { degrees: 100.0, scale: Scale::Celsius, sensor_id: 4 }; for t in [&body, &boiling] { // the sensor id has nothing to do with the scale, so just read the field println!("sensor {}: {:.1} C", t.sensor_id, t.in_celsius()); } }
Temperature as an enum. Same output, but reading the sensor id takes a match whose two arms do the same thing.
enum Temperature { Fahrenheit(f64, u32), // degrees, sensor id Celsius(f64, u32), // degrees, sensor id } impl Temperature { // converting needs the scale fn in_celsius(&self) -> f64 { match self { &Temperature::Celsius(degrees, _) => degrees, &Temperature::Fahrenheit(degrees, _) => (degrees - 32.0) * 5.0 / 9.0, } } // the sensor id has nothing to do with the scale, and we still have to ask fn sensor_id(&self) -> u32 { match self { &Temperature::Fahrenheit(_, id) => id, &Temperature::Celsius(_, id) => id, } } } fn main() { let body = Temperature::Fahrenheit(98.6, 7); let boiling = Temperature::Celsius(100.0, 4); for t in [&body, &boiling] { println!("sensor {}: {:.1} C", t.sensor_id(), t.in_celsius()); } }
Project 1's SecretKeeper. The one you saw on Monday was trimmed. Here is the field the real one has:
enum Source {
Human,
Known(u32),
}
pub struct SecretKeeper {
source: Source,
questions: u32,
already_used: Vec<u32>,
}
There is no secret field. A keeper either asks the person at the keyboard, or it is already holding a number. Only one of those two carries a u32, so the number lives inside the variant.
Why not a secret field with a human flag next to it? Because then a Human keeper would still have a secret number sitting inside it, and nothing would stop you reading it. The enum makes the impossible combination impossible to write down: if it is Human, there is no number to read.
Lecture 13 - Errors: Result, Option, and reading a file
Announcements
Learning objectives
By the end of today, you should be able to:
- Say what
panic!does, and call it directly or throughunwrapandexpect - Decide when to panic and when to return a
Result, and defend the choice - Write a function that returns
Result<T, E>and handle both cases at the call site - Use
matchand?to handle an error or pass it up - Read a file and write a file, and deal with the
Resulteach one hands back
Part 1: A program that needs all this
So you want to read a file
Your data is in a file. You want it in a String. This should be one line:
fn main() {
let text = std::fs::read_to_string("data.csv");
println!("{}", text);
}
It does not compile.
The compiler says what you actually got
error[E0277]: `Result<String, std::io::Error>` doesn't implement `std::fmt::Display`
--> src/main.rs:3:20
|
3 | println!("{}", text);
| -- ^^^^ `Result<String, std::io::Error>` cannot be formatted
You asked for a String. You got a Result<String, std::io::Error>.
Rust will not let you use the text until you have said what happens when there is no text.
That is the whole lecture. Every language has this problem. Rust is the one that makes you answer it before the program runs.
Rust's Error Philosophy: Errors as Data
Most languages: Errors are "exceptional" events that get thrown and caught
try:
result = divide(a, b)
# continue with result
except DivisionByZeroError:
# handle error
Rust: Errors are just another kind of data that functions can return
match divide(a, b) {
Ok(result) => { /* continue with result */ },
Err(error) => { /* handle error */ },
}
Error Handling in Rust
Two basic options:
- terminate when an error occurs: macro
panic!(...) - pass information about an error: enum
Result<T,E>
Option 1: Choose to panic!
What it means to panic:
- stops execution ("crashes")
- starts "unwinding the stack" (more on that later)
- prints a message to the console
- tells us where in the code the panic occurred
Macro panic!(...)
- Use for unrecoverable errors
fn divide(a:u32, b:u32) -> u32 { if b == 0 { panic!("I'm sorry, Dave. I'm afraid I can't do that."); } a/b } fn main() { println!("{}",divide(20,7)); // println!("{}",divide(20,0)); }
Getting more info out of a panic!
- Use
RUST_BACKTRACE=1 cargo runto get a backtrace like this:
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99
stack backtrace:
0: rust_begin_unwind
at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/std/src/panicking.rs:692:5
1: core::panicking::panic_fmt
at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:75:14
2: core::panicking::panic_bounds_check
at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:273:5
3: <usize as core::slice::index::SliceIndex<[T]>>::index
at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:274:10
4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:16:9
5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:3361:9
6: panic::main
at ./src/main.rs:4:6
7: core::ops::function::FnOnce::call_once
at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
Shortcuts to panic!
Both unwrap and expect will call panic! if there is an error.
use std::fs::File; fn main() { let greeting_file = File::open("hello.txt").unwrap(); println!("{:?}", greeting_file); }
use std::fs::File; fn main() { let greeting_file = File::open("hello.txt") .expect("hello.txt should be included in this project"); println!("{:?}", greeting_file); }
expect takes a message and unwrap does not, which is the whole difference. Write what you assumed, not what broke: "hello.txt should be included in this project" tells whoever reads the crash why the assumption was wrong. That is usually you, three weeks later.
Quick Quiz
1. Which #[derive()] trait lets you print an enum with {:?}?
2. Why won't this compile?
#![allow(unused)] fn main() { enum Status { Loading, Complete, Error, } let status = Status::Complete; match status { Status::Complete => println!("Finished!"), Status::Error => println!("An error has occurred!"), } }
3. What do you think this will print?
#![allow(unused)] fn main() { let result = Some(42); match result { Some(x) if x > 40 => println!("Large: {}", x), Some(x) => println!("Small: {}", x), None => println!("Nothing"), } }
Recap: Option<T>
Wednesday's problem: Python's find_index returns -1 for a missing name, and last_names[-1] quietly prints the wrong person.
Rust's answer is a built-in enum with two variants:
enum Option<T> {
Some(T),
None,
}
Some(T)holds the valueNonemeans there isn't one, and that is a normal answer, not a failure- You can't use the value until you've opened it, and
matchmakes you say what happens onNone
match find_index("Totoro", names) {
Some(i) => println!("{} {}", "Totoro", last_names[i]),
None => println!("Totoro is not in the list"),
}
Option<T>: useful methods
match always works, but a few methods cover the common cases in one line.
Check the variant
.is_some() -> bool.is_none() -> bool
Get the value in Some, or a default if there isn't one
.unwrap_or(default_value: T) -> T
fn find_index(target: &str, names: [&str; 3]) -> Option<usize> { for i in 0..names.len() { if target == names[i] { return Some(i); } } None } fn main() { let names = ["Kesar", "Mei", "Satsuki"]; let found = find_index("Mei", names); let missing = find_index("Totoro", names); println!("{} {}", found.is_some(), missing.is_some()); println!("{}", missing.is_none()); println!("{} {}", found.unwrap_or(99), missing.unwrap_or(99)); }
true false
true
1 99
unwrap and expect work on Option too
Same two methods as on the panic! slide, and they panic the same way.
Option says there might be nothing; unwrap is you saying there is:
fn find_index(target: &str, names: [&str; 3]) -> Option<usize> { for i in 0..names.len() { if target == names[i] { return Some(i); } } None } fn main() { let names = ["Kesar", "Mei", "Satsuki"]; println!("{}", find_index("Mei", names).unwrap()); println!("{}", find_index("Totoro", names).expect("Totoro should be in the list")); }
1
thread 'main' panicked at src/main.rs:13:48:
Totoro should be in the list
Option can tell you there's nothing. It can't tell you why. When the caller needs the why, you want Result.
Enum Result<T,E>
enum Result<T,E> {
Ok(T),
Err(E),
}
Functions can use it to
- return a result
- or information about an encountered error
fn divide(a:u32, b:u32) -> Result<u32, String> { if b != 0 { Ok(a / b) } else { let str = format!("Division by zero {} {}", a, b); Err(str) } } fn main(){ println!("{:?}",divide(20,7)); // println!("{:?}",divide(20,0)); }
Opening a Result
Ok and Err are variants, so match gets the value back out. This is the skeleton from the start of class, filled in:
fn divide(a: u32, b: u32) -> Result<u32, String> { if b != 0 { Ok(a / b) } else { let str = format!("Division by zero {} {}", a, b); Err(str) } } fn main() { match divide(20, 7) { Ok(answer) => println!("got {}", answer), Err(message) => println!("failed: {}", message), } match divide(20, 0) { Ok(answer) => println!("got {}", answer), Err(message) => println!("failed: {}", message), } }
got 2
failed: Division by zero 20 0
Neither call crashed! The second one failed, explained why, and let the program keep going. That is the whole difference between handing back a Result and calling panic!.
parse hands back a Result too
Remember parse? It also returns a Result to handle cases when parse... can't.
fn main() { match "42".parse::<i32>() { Ok(number) => println!("got {}", number), Err(problem) => println!("failed: {}", problem), } match "4x2".parse::<i32>() { Ok(number) => println!("got {}", number), Err(problem) => println!("failed: {}", problem), } }
got 42
failed: invalid digit found in string
Same shape as the last slide, different function. The ::<i32> says which type to aim for, since parse can produce plenty of them.
When to use Option<T>, Result<T,E>, and panic!
- Use
Option<T>when there might be nothing, and nothing is a normal answer: the name is not in the list - Use
Result<T,E>when you want to handle the error and continue execution, and the caller deserves to know what went wrong: the file is not there - Use
panic!when the error is unrecoverable
The tell between the first two: if you have to invent an error message to explain the empty case, you wanted Option. If you already have one, you wanted Result.
Concept: Propagating Errors
Error propagation means passing errors up through layers of function calls.
Think of it like a company hierarchy:
- Junior developer encounters a bug they can't fix, reports it to senior developer
- Senior dev can't solve it, escalates to team lead
- Each level decides: "Can I handle this?" or "Pass it up the chain"
Or like the court system:
- Local court -> Appeals court -> State supreme court -> Federal supreme court
- Each level can either handle the case or pass it to a higher authority
Different jobs for different functions:
- Low-level functions know what went wrong, but not what to do about it
- High-level functions have context to decide how to respond to different errors
Propagating errors in Rust
- We are interested in the positive outcome:
tinOk(t) - But if an error occurs, we want to propagate it ("pass the buck")
- This can be handled using
matchstatements
// compute a/b + c/d fn calculate(a:u32, b:u32, c:u32, d:u32) -> Result<u32, String> { let first = match divide(a,b) { Ok(t) => t, Err(e) => return Err(e), }; let second = match divide(c,d) { Ok(t) => t, Err(e) => return Err(e), }; Ok(first + second) } fn divide(a:u32, b:u32) -> Result<u32, String> { if b != 0 { Ok(a / b) } else { let str = format!("Division by zero {} {}", a, b); Err(str) } } fn main(){ println!("{:?}", calculate(16,4,18,3)); println!("{:?}", calculate(16,0,18,3)); }
return inside an arm returns from the whole function, not from the match. The Err arm never hands a value back to let first, because by then we are already gone.
The question mark shortcut
-
Place
?after an expression that returnsResult<T,E> -
This will:
- give the content of
Ok(t) - or return
Err(e)from the encompassing function
- give the content of
fn calculate(a:u32, b:u32, c:u32, d:u32) -> Result<u32, String> { Ok(divide(a,b)? + divide(c,d)?) } fn divide(a:u32, b:u32) -> Result<u32, String> { if b != 0 { Ok(a / b) } else { let str = format!("Division by zero {} {}", a, b); Err(str) } } fn main(){ println!("{:?}", calculate(16,4,18,3)); println!("{:?}", calculate(16,0,18,3)); }
Caution with ?
The ? operator can only be used in functions whose return type is compatible with the value the ? is used on.
- If you use
?on aResult<T,E>, the function must returnResult<..., E>(with the sameE!) - If you use
?on anOption<T>, the function must returnOption<...>.
Back to reading a file...
use std::fs; fn main() { match fs::read_to_string("data.csv") { Ok(text) => println!("read {} bytes", text.len()), Err(e) => println!("could not read it: {}", e), } fs::write("out.txt", "hello from Rust\n").expect("could not write out.txt"); }
fs::read_to_string gives you the whole file as a String. fs::write puts a string in a file, creating it or replacing what was there.
Both hand back a Result, because both can fail.
read_to_string reads the whole file into memory at once. Fine for a homework CSV, a bad idea for a 40GB log. Lecture 36 covers reading a line at a time.
Activity Time
On paper, on your own. Put your name on the sheet and hand it in at the end.
See Activity 13
Lecture 14 - Match, again: patterns, arms, and getting the value out
Announcements
Learning objectives
By the end of today, you should be able to:
- Say which arm of a
matchruns for a given value, and why order matters - Say what can go after
match, and what a pattern is - Explain what an arm hands back, and what
returninside an arm does - Get the value out of an
Option, aResult, or your own enum, and use it after thematch - Match on an enum that is a field of a struct, inside a method
Friday's exam: six sections
50 minutes, 100 points. Lectures 1-13. No notes, no devices. Six sections:
1. Quick recall (14 pts, ~5 min). Fill in a blank, one word or one line.
- Example: a
u8holds values from 0 to____ - Practice: Activity 6, Activity 14 Part 2
2. A day of work (10 pts, ~5 min). Shell and git commands for a scenario.
- Example: which command copies a repo from GitHub onto your machine?
- Practice: Activity 2, Discussion 2, the Lecture 2 quiz, Activity 14 Part 1
3. What does this print (16 pts, ~7 min). Trace a short program and write its exact output.
- Example:
let mut n = 1; while n < 20 { n = n * 3; } println!("{}", n); - Practice: Activity 8 Part 1, Activity 14 Part 3, today's "which arm?"
4. Read the error, fix the bug (16 pts, ~8 min). Code with line numbers, plus the compiler's error. Give the line number and the line as it should read.
- Example: line 3 is
fn bump(&self) {, line 4 isself.hits += 1;, and the error iscannot assign to self.hits, which is behind a & reference - Practice: Activity 5, Activity 8 Part 4, today's "does it compile?" and spot the bug
5. Hand-coding (24 pts, ~11 min). Write two functions on paper. Sometimes you write the signature too.
- Example: write
count_negative, which takes[i32; 5]and returns how many are below zero - Practice: Activities 7, 12, 13, Discussion 4, today's "write it" problems
6. Compare two programs (20 pts, ~8 min). Two working programs: time and space complexity, then which you would use and why.
- Example: find the largest number by sorting and taking the last one, or by one pass keeping the biggest so far
- Practice: Activities 9 and 10, Lecture 15's complexity questions
For a complete list of content coverage - see Lecture 15 (Wednesday, and online already)
For even more practice questions - AI can probably riff on these to quiz you in these formats. We can also generate them on the fly in office hours.
Part 1: What match does
A coin sorter
A coin goes in at the top. It slides past a row of slots. It drops through the first one it fits.
match is the same machine:
- One value goes in
- It is checked against each pattern, top to bottom
- The first pattern it fits wins, and that arm runs
- Nothing below it is checked
- Everything has to land in a slot (not allowed to roll off the machine!)
The parts of match
match coin { // the value going in
Coin::Penny => 1, // pattern => what this arm hands back
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
- After
match: a value - Left of
=>: a pattern, a shape the value might have - Right of
=>: an expression, what this arm does or hands back - A comma between arms
What can go after match
Anything that has a value:
match coin { ... } // a variable
match customer.state { ... } // a field of a struct
match divide(10, 2) { ... } // a function call
match "42".parse::<i32>() { ... } // a method call
match n % 2 { ... } // arithmetic
The type of that value decides what the patterns look like. A Coin gets coin patterns. An Option<u32> gets Some(...) and None.
What a pattern is
A pattern is a shape. Some shapes are exact. Some have a hole in them.
| Pattern | What fits | Makes a new variable? |
|---|---|---|
Coin::Dime | exactly that variant | No |
0 | exactly that number | No |
Some(0) | a Some with exactly 0 inside | No |
Some(n) | any Some, whatever is inside | Yes, n |
n | anything at all | Yes, n |
_ | anything at all | No, it throws it away |
A name in a pattern is a hole. Whatever fills the hole gets that name, for that one arm.
Rust has never seen n before. The pattern is what creates it.
Think-pair-share: which arm?
fn describe(winnings: Option<u32>) { match winnings { Some(0) => println!("A: nothing won"), Some(n) if n > 100 => println!("B: big win, {}", n), Some(n) => println!("C: won {}", n), None => println!("D: did not play"), } } fn main() { for w in [Some(5), Some(0), None, Some(250), Some(100)] { describe(w); } }
Which letter prints for each?
Some(5) Some(0) None Some(250) Some(100)
Answer. C, A, D, B, C.
Swap A and C and every Some lands in C, including Some(0). The compiler warns unreachable pattern on A.
Part 2: What comes out of an arm
match hands back a value
The whole match is an expression, so you can store it:
#[allow(dead_code)] enum Coin { Penny, Nickel, Dime, Quarter } fn main() { let coin = Coin::Dime; let cents = match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, }; println!("{}", cents); }
Every arm hands back the same type. Rust has to know what type cents is before it knows which arm will run.
Note the ; after the closing }. It ends the let, not the match.
An arm can be a block
#[allow(dead_code)] enum Coin { Penny, Nickel, Dime, Quarter } fn main() { let coin = Coin::Quarter; let cents = match coin { Coin::Penny => 1, Coin::Quarter => { println!("Lucky quarter!"); 25 // no semicolon: this is the arm's value }, _ => 0, }; println!("{}", cents); }
The last line of the block, with no semicolon, is what the arm hands back. Same rule as a function body.
Arms that print
match winnings {
Some(n) => println!("won {}", n),
None => println!("did not play"),
}
println! hands back (), which is Rust for "nothing". So every arm here hands back (), the arms agree, and nothing gets stored. Fine.
Think-pair-share: does it compile?
(a)
match coin {
Coin::Penny => println!("1 cent"),
_ => ()
}
(b)
let label = match coin {
Coin::Penny => "small",
Coin::Quarter => 25,
_ => "medium",
};
(c)
let cents = match coin {
Coin::Penny => 1,
Coin::Quarter => {
println!("Lucky!");
25;
}
_ => 0,
};
(d)
fn bonus(level: u32) -> u32 {
match level {
1 => 10,
2 => 20,
3 => 50,
}
}
Answer.
(a) Yes. Both arms return ().
(b) No. match arms have incompatible types.
(c) No. The semicolon after 25 turns it into a statement, so that block hands back () while the others hand back numbers. The compiler even says help: consider removing this semicolon.
(d) No. A u32 has about four billion values, and three arms cover three of them:
error[E0004]: non-exhaustive patterns: `0_u32` and `4_u32..=u32::MAX` not covered
Exhaustive means every possible value, not only enum variants. Add _ => 0 to fix.
Part 3: Getting the value out
The name only lives inside its arm
match find_index("Mei", names) {
Some(i) => println!("found at {}", i),
None => println!("not found"),
}
println!("{}", last_names[i]); // error: cannot find value `i`
i was made by the pattern, so it ends with the arm. Two ways out:
- Hand the value back into a
let, and use it afterwards - Do the work inside the arm
Hand it back into a let
fn ticket_price(age: Option<u32>) -> u32 { let age = match age { Some(a) => a, // hand back what was inside None => return 15, // no age given: full price, and leave now }; // from here on, age is a plain u32 if age < 12 { 8 } else { 15 } } fn main() { println!("{}", ticket_price(Some(9))); println!("{}", ticket_price(Some(40))); println!("{}", ticket_price(None)); }
return inside an arm leaves the whole function, not just the match. The None arm never hands anything to let age, because by then we are gone.
Do the work in an arm
fn ticket_price(age: Option<u32>) -> u32 { match age { Some(a) => if a < 12 { 8 } else { 15 }, None => 15, } } fn main() { println!("{}", ticket_price(Some(9))); println!("{}", ticket_price(Some(40))); println!("{}", ticket_price(None)); }
Or on the pattern side,
fn ticket_price(age: Option<u32>) -> u32 { match age { Some(a) if a < 12 => 8, Some(_) => 15, None => 15, } } fn main() { println!("{}", ticket_price(Some(9))); println!("{}", ticket_price(Some(40))); println!("{}", ticket_price(None)); }
A shape to remember
let value = match something_that_might_not_work {
Some(v) => v, // or Ok(v) => v
None => ..., // or Err(e) => ...
};
The second arm is the decision. Three choices:
- A default:
None => 0 - Give up on this function:
None => return None, orErr(e) => return Err(e) - Crash:
None => panic!("...")
Choice 2, with Result, is exactly what ? writes for you.
The same shape, with Result
fn total_bet(a: &str, b: &str) -> Result<u32, String> { let first = match a.parse::<u32>() { Ok(n) => n, Err(_) => return Err(format!("'{}' is not a bet", a)), }; let second = match b.parse::<u32>() { Ok(n) => n, Err(_) => 0, // the second bet is optional }; Ok(first + second) } fn main() { println!("{:?}", total_bet("10", "5")); println!("{:?}", total_bet("10", "x")); println!("{:?}", total_bet("ten", "5")); }
Ok(15)
Ok(10)
Err("'ten' is not a bet")
Two matches, two different decisions about the error arm.
Think-pair-share: write it
A game has four levels. Each one is Some(coins) if you finished it, None if you did not.
(a) Add up the coins from the levels you finished.
fn total_coins(levels: [Option<u32>; 4]) -> u32 {
// your code here
}
| Call | Returns |
|---|---|
total_coins([Some(3), None, Some(10), Some(0)]) | 13 |
total_coins([None, None, None, None]) | 0 |
(b) If you finish early: the same, but None unless every level was finished.
fn total_if_complete(levels: [Option<u32>; 4]) -> Option<u32> {
// your code here
}
Answer.
fn total_coins(levels: [Option<u32>; 4]) -> u32 { let mut total = 0; for level in levels { match level { Some(coins) => total += coins, None => () } } total } fn total_if_complete(levels: [Option<u32>; 4]) -> Option<u32> { let mut total = 0; for level in levels { match level { Some(coins) => total += coins, None => return None, // any unfinished: give up } } Some(total) } fn main() { println!("{}", total_coins([Some(3), None, Some(10), Some(0)])); println!("{}", total_coins([None, None, None, None])); println!("{:?}", total_if_complete([Some(3), None, Some(10), Some(0)])); println!("{:?}", total_if_complete([Some(3), Some(4), Some(10), Some(0)])); }
The only differences in (b): the None arm returns, and the end wraps total in Some.
Part 4: An enum inside a struct
Back to Alice
Last week we fixed Customer so state is an enum, not a String. Now let's compute her shipping cost:
#![allow(dead_code)] enum State { NY, MA, CA } struct Customer { name: String, state: State, member: bool, } impl Customer { fn shipping_cost(&self) -> f64 { match self.state { State::NY => 5.00, State::MA => 7.50, State::CA => 12.00, } } } fn main() { let alice = Customer { name: String::from("Alice"), state: State::NY, member: false }; println!("{} pays {:.2}", alice.name, alice.shipping_cost()); let _ = alice.member; }
What goes after match? self.state, a field. Its type is State, so the patterns are states.
Outside a method it is the same thing with a different name: match alice.state { ... }.
When the variant carries data
enum Status {
Active,
Injured(u32), // games left to sit out
Retired,
}
struct Player {
name: String,
status: Status,
}
Think-pair-share: write it
Write report, a method on Player that prints one line:
Totoro: active
Mei: injured, games left to sit out: 2
Satsuki: retired
impl Player {
fn report(&self) {
// your code here
}
}
If you're done: Write next_game(&mut self). An injured player has one fewer game to sit out, and is Active again when it reaches zero. Everyone else is unchanged.
Answer.
#![allow(dead_code)] enum Status { Active, Injured(u32), Retired, } struct Player { name: String, status: Status, } impl Player { fn report(&self) { match self.status { Status::Active => println!("{}: active", self.name), Status::Injured(games) => println!("{}: injured, games left to sit out: {}", self.name, games), Status::Retired => println!("{}: retired", self.name), } } fn next_game(&mut self) { match self.status { Status::Injured(1) => self.status = Status::Active, Status::Injured(games) => self.status = Status::Injured(games - 1), _ => () } } } fn main() { let mut mei = Player { name: String::from("Mei"), status: Status::Injured(2) }; mei.report(); mei.next_game(); mei.report(); mei.next_game(); mei.report(); }
games is a hole, same as n in Some(n). self.name comes from the struct, and games comes from the variant.
In the stretch, Injured(1) has to sit above Injured(games), or the general arm catches it first. And it is &mut self because it changes self.status.
Part 5: Spot the bug
Three bugs from real(istic) hand-coding
Each one does not compile. What is wrong, and what is the simplest fix?
find_index returns an Option<usize>
1.
if find_index("Mei", names) == 1 {
println!("Mei is second");
}
2.
match find_index("Mei", names) {
Some(i) => println!("found"),
None => println!("not found"),
}
println!("{}", last_names[i]);
3.
fn half(n: u32) -> Option<u32> {
if n % 2 == 0 {
n / 2
} else {
None
}
}
Answer.
find_indexhands back anOption<usize>, not a number, and anOptionis never equal to1. Compare againstSome(1), or open it with amatchionly exists inside theSomearm. Move theprintln!into that arm- The return type promises an
Option, so the even case needsSome(n / 2).
Part 6: A pep talk for your first code review
What a code review is not
A search for what you got wrong.
The autograder already did that.
What it actually is
Somebody opens your repo, reads your code and your commit history, and asks you why.
Why this approach. What you tried first. What happens if the input changes.
Expect it to be uncomfortable
Remember:
- It is a conversation about choices, not a search for defects
- Not knowing is allowed. But dishonesty will bite you.
"I don't know why that works, I tried it after the other version panicked" is a good answer. It is honest, it says what you did, and it is something we can talk about.
Activity time
See Activity 14
You'll write how you feel, not answers.
You'll take a photo and submit it on gradescope so you can keep the paper for studying.
Lecture 15 - Review: everything before Midterm 1
Welcome to Review Day!
You've learned a lot in just a few weeks! Today we'll:
- Review key concepts you need to master for the midterm
- Practice with interactive questions
- Clarify what you need to know vs. what's just context
- Build confidence for the exam
Reminders about the exam
- Friday during your usual class time
- No reference sheets or calculators
- Two exam versions and set (but not assigned) seating
And two things to keep in mind when this feels hard
- Corrections. About two weeks after the exam, in discussion, you can redo specific questions and earn back up to half your lost points.
- A strong final counts for more. If your final beats your midterm average, we reweight automatically and use whichever calculation is better for you.
Shell/Terminal Commands (Lecture 2)
For the midterm, you should recognize and recall:
pwd- where am I?ls- what's here?ls -la- more info and hidden filesmkdir folder_name- make a foldercd folder_name- move into a foldercd ..- move up to a parent foldercd ~- return to the home directoryrm filename- delete a filerm -rf folder_name- delete a folder and everything in it, no questions askedtouch filename- make an empty filecat filename- print a whole file to the screennano filename- edit a file without leaving the terminalcp file.txt backup.txt- copy a filemv old_name new_name- rename or move a fileecho "text" > file.txt- write text to a file, replacing what was thereecho "text" >> file.txt- add text to the end of a file
You DON'T need to: Memorize complex command flags, pipes, file permissions, or shell scripting
Git Commands (Lecture 4)
For the midterm, you should recognize and recall:
git clone- get a repository, pasting in the HTTPS or SSH linkgit init- start tracking the folder you are standing ingit status- see what's changedgit diff- see exactly what changed since the last commitgit add .- stage all recent changesgit commit -m "my commit message"- create a commit with staged changesgit push- send what's on my machine to GitHubgit pull- get changes from GitHub to my machine
You DON'T need to: type merge, revert, reset, checkout, or pull request commands from memory
You DO need the ideas: what a branch is, what merging does, and what a merge conflict is, including roughly how you sorted out the one in Project 1
Cargo Commands (Lecture 5)
For the midterm, you should recognize and recall:
cargo new project_name- create projectcargo run- compile and runcargo run --release- compile and run with optimizations (slower to compile, faster to run)cargo build- just compile without runningcargo check- just check for errors without compilingcargo test- run tests
You DON'T need to know: Cargo.toml syntax, how Cargo.lock works, or advanced cargo features
You DO need to read a compiler error: find the file and line it names, read what it says it expected and what it found, and use the suggestion. Remember that the fix does not always belong on the line the error points at.
Quick Questions: Tools
Question 1
Name the command that:
- a) shows your current location on your machine
- b) compiles your code without running it
Answer. a) pwd. b) cargo build. (cargo check looks for errors but never produces a program you could run.)
Question 2
What's the correct order for the basic Git workflow?
- A) add -> commit -> push
- B) commit -> add -> push
- C) push -> add -> commit
- D) add -> push -> commit
Answer. A. add, then commit, then push. Staging comes first, the commit packages what is staged, and the push sends it to GitHub.
Compilers vs Interpreters (Lecture 3)
Key Concepts
- Compiled languages (like Rust): Code is transformed into machine code before running
- Interpreted languages (like Python): Code is executed line-by-line at runtime
- The compiler checks your code for errors and translates it into machine code
- The machine code is directly executed by your computer - it isn't Rust anymore!
- A compiler error means your code failed to translate into machine code
- A runtime error means your machine code crashed while running
Rust prevents many runtime errors by being strict at compile time!
Variables and Types (Lecture 6)
Key Concepts
- Defining variables:
let x = 5; - Mutability: Variables are immutable by default, use
let mutto allow them to change - Shadowing:
let x = x + 1;creates a newxvalue withoutmutand lets you change types. A variable that's shadowed inside a scope ({}) is visible again after the scope ends. - Basic types:
i32,f64,bool,char,&str,String - Rough variable sizes: Eg.
i32takes up 32-bits of space and its largest positive value is about half ofu32's largest value - Type annotations: Rust infers types (
let x = 5) or you can specify them (let x: i32 = 5) - Tuples: Creating (
let x = (2,"hi")), accessing (let y = x.0 + 1), destructuring (let (a,b) = x) - Constants: Eg.
const MY_CONST: i32 = 5, always immutable, must have explicit types, written into machine code at compile-time - Two's complement: how a signed integer holds a negative number. Flip every bit, add one. A leading
1means negative, so as ani8,1111 1111is-1and not255
What's Not Important
- Calculating exact variable sizes and max values
- Complex string manipulation details
String vs &str - You're not responsible for it, but let's refresh
Quick explanation
String= a string = owned text data (like a text file you own)&str= a string slice = borrowed text data (like looking at someone else's text)- A string literal like
"hello"is a&str(you don't own it, it's baked into your program) - To convert from an &str to a String, use
"hello".to_string()orString::from("hello") - To convert from a String to an &str, use
&my_string(to create a "reference")
Don't stress! You can do most things with either one, and I will not make you do anything crazy with these / penalize you for misusing these on the midterm.
Quick Questions: Rust basics
Question 3
What happens with this code?
#![allow(unused)] fn main() { let x = 5; x = 10; println!("{}", x); }
- A) Prints 5
- B) Prints 10
- C) Compiler error
- D) Runtime error
Answer. C, compiler error. x is immutable. let mut x = 5; fixes it.
Question 4
What's the type of x after this code?
#![allow(unused)] fn main() { let x = 5; let x = x as f64; let x = x > 3.0; }
- A)
i32 - B)
f64 - C)
bool - D) Compiler error
Answer. C, bool. Each let x shadows the one before it and is allowed to change the type: i32, then f64, then the result of a comparison.
Question 5
How do you access the second element of tuple t = (1, 2, 3)?
- A)
t[1] - B)
t.1 - C)
t.2 - D)
t(2)
Answer. B, t.1. Tuples use a dot and a number. Square brackets are for arrays and vectors.
Functions (Lecture 7)
Key Concepts
- Function signature:
fn name(param1: type1, param2: type2) -> return_type, returned value must matchreturn_type - Expressions and statements: Expressions reduce to values (no semicolon), statements take actions (end with semicolon)
- Returning with return or an expression: Ending a function with
return x;andxare equivalent - {} blocks are scopes and expressions: They reduce to the value of the last expression inside them
- Unit type: Functions without a return type return
() - Best practices: Keep functions small and single-purpose, name them with verbs
What's Not Important
- Ownership/borrowing mechanics (we'll cover this after the midterm)
- Advanced function patterns
Quick Questions: Functions
Question 6
What is the value of mystery(x)?
#![allow(unused)] fn main() { fn mystery(x: i32) -> i32 { x + 5; } let x = 1; mystery(x) }
- A) 6
- B)
i32 - C)
() - D) Compiler error
And if the return type were dropped, fn mystery(x: i32), what would change?
Answer. D, compiler error. The semicolon after x + 5 turns the body into a statement, so the function hands back () while its signature promises i32. Drop the semicolon, or write return x + 5;.
If -> i32 were dropped, it would compile, because () is then exactly what the signature says. mystery(x) would be ().
Question 7
Which is a correct function signature for a function that takes two integers and returns their sum?
Answer. fn add(a: i32, b: i32) -> i32. The names are up to you, and so is which integer type. Every parameter needs a type, and the return type comes after ->.
Control Flow and Arrays (Lecture 8)
Key Concepts
- Ranges:
1..5vs1..=5 - Arrays: Creating (
[5,6]vs[5;6]), accessing (x[i]), 0-indexing - If/else: how to write
if / elseblocks with correct syntax - Loop types:
for,while,loop- how and when to use each breakandcontinue: For controlling loop flow- Basic enumerating
for (i, val) in x.iter().enumerate()
What's Not Important
- Compact notation (
let x = if y ...orlet y = loop {...) - Enumerating over a string array with
for (i, &item) in x.iter().enumerate() - Labeled loops, breaking out of an outer loop
Quick Questions: Control Flow & Arrays
Question 8
- a) What's the difference between
1..5and1..=5? - b) How do you get both the index and the value when looping over an array?
Answer. a) 1..5 is 1, 2, 3, 4. 1..=5 also includes 5. b) for (i, val) in x.iter().enumerate().
Question 9
What does this print?
#![allow(unused)] fn main() { for i in 0..3 { if i == 1 { continue; } println!("{}", i); } }
Answer. 0, then 2. When i is 1, continue skips the println! and starts the next pass.
Comparing Programs (Lecture 9)
Key Concepts
- Timing two programs that do the same thing, and why debug and release give different numbers
- Counting steps: how many operations a piece of code does, and how that count grows as the input grows
- Big O notation: describing that growth for time and for space
- The common classes: O(1), O(log n), O(n), O(n^2), O(2^n), and what each one feels like as n gets big
- The two rules: drop constants, keep the dominant term.
O(3n + 7)isO(n) - Reading a loop: one loop over n is O(n), a loop inside a loop is usually O(n^2)
What's Not Important
- Formal proofs, or the difference between big O, big theta, and big omega
- Amortized analysis
- Memorizing complexity numbers you have not derived
Sorting and Recursion (Lecture 10)
Key Concepts
- Sorting by hand: selection sort and insertion sort, step by step on a small list
- Finding their Big O from the loops: both are O(n^2), and you should be able to say why
- Recursion: a base case plus a smaller version of the same problem, and what happens without a base case
- Merge sort is O(n log n), from the shape of its call tree: log n levels, n work per level
What's Not Important
- Writing merge sort from scratch
- Quicksort, heapsort, or sort stability
- The exact number of swaps or comparisons for a given list
Quick Questions: Complexity & Sorting
Question 10
What is the Big O of this, in terms of n?
#![allow(unused)] fn main() { for i in 0..n { for j in 0..n { println!("{}", i * j); } } }
- A) O(1)
- B) O(n)
- C) O(n^2)
- D) O(2^n)
Answer. C, O(n^2). A loop over n, inside a loop over n.
Question 11
A program is O(n^2). You double the size of the input. Roughly how much longer does it take?
Answer. About four times as long. Double the input and n^2 becomes (2n)^2, which is 4n^2.
Question 12
What is missing here, and what happens when you run it?
#![allow(unused)] fn main() { fn countdown(n: u32) { println!("{}", n); countdown(n - 1); } }
Answer. There is no base case, so it never stops calling itself. It crashes before it gets far, though: once n reaches 0, n - 1 goes below zero, which a u32 cannot hold, and the program panics with attempt to subtract with overflow. Add if n == 0 { return; } at the top to fix.
Question 13
Merge sort is O(n log n). Where does the log n come from?
Answer. From halving. The list splits in half each time, so it takes about log(n) splits to get down to single elements. That is the number of levels in the call tree, and every level does n work merging back together.
Structs (Lecture 11)
Key Concepts
- Defining a struct:
struct Customer { name: String, age: u32 }, and making one - Reading and writing fields with a dot, and that
mutapplies to the whole struct - Tuple structs for when the fields don't need names
implblocks: writing a method and calling it with a dot&selfvs&mut self: read the struct, or change it. Plainselftakes it with you- Constructors:
Customer::new(...), and why it is::and not. Vec: a list that can grow,push,len, and indexing
What's Not Important
- Deriving anything beyond
Debug - Generic structs, or lifetimes on a struct
Box, trait objects, and anything else that comes after the midtermpub: not on Friday. It comes back properly when we do modules and crates
Quick Questions: Structs
Question 14
What happens with this code?
#![allow(unused)] fn main() { struct Point { x: f64, y: f64 } let p = Point { x: 1.0, y: 2.0 }; p.x = 5.0; }
- A) Prints nothing, runs fine
- B) Compiler error
- C) Runtime error
- D)
p.xis 1.0 afterwards
Answer. B, compiler error. p is not mut, so none of its fields can be written. let mut p = ... fixes it.
Question 15
What goes in the blank?
#![allow(unused)] fn main() { impl Rectangle { fn area(____) -> f64 { self.width * self.height } } }
Answer. &self. The method reads self.width and self.height and changes nothing, so it only needs to borrow.
Question 16
Why is it Customer::new("Alice") and not customer.new("Alice")?
Answer. new is an associated function, not a method: notice it takes no self. There is no Customer yet to put on the left of a dot, so you reach through the type itself with ::.
Enums and Pattern Matching (Lecture 12)
Key Concepts
- Enum definition: Creating custom types with variants
- Data in variants: Enums can hold data
matchexpressions: syntax by hand, needs to be exhaustive, how to use a catch-all (_)Option<T>: HasSome(value)andNone, for when there might be nothing#[derive(Debug)]: For making enums printable#[derive(PartialEq)]: For allowing enums to be compared with==and!=- Data extraction: Getting values out of enum variants with
match. ForOptionspecifically, alsounwrapandexpect - Pattern guards: an arm with a condition on it,
Some(x) if x > 40 => ...
What you should be able to write
- A
matchon an enum, covering every variant - A guard, which is just a condition on the arm. That is the flexible one
What's Not Important
if letnotation- Writing the other pattern shapes from memory (ranges, tuples, arrays, struct patterns). You should be able to read a variety of them
Quick Questions: Enums & Match
Question 17
What's wrong with this code?
#![allow(unused)] fn main() { enum Status { Loading, Complete, Error, } match Status::Loading { Status::Loading => println!("Loading..."), Status::Complete => println!("Done!"), } }
Answer. The match is not exhaustive. Status::Error has no arm, so this does not compile. Add an arm for it, or a _ catch-all.
Question 18
If a function's return type is Option<i32> what values can it return (can be more than one)?
- A)
Some(i32) - B)
Ok - C)
Ok(i32) - D)
None - E)
Err
Answer. A and D. Some(i32) or None. Ok and Err belong to Result, not Option.
Question 19
Which of these can go in the ???? to print Got: 42? More than one works.
#![allow(unused)] fn main() { let x = Some(42); match x { Some(????) => println!("Got: {}", ????), None => println!("Nothing"), } }
- A)
_and_ - B)
42and42 - C)
xandx - D)
yandy
Answer. C and D both work.
y is the best answer, but x works too, because inside the arm, x is a new variable holding 42, shadowing the outer x. But it's confusing to read.
A fails because _ cannot be used as a value. B fails for a different reason: Some(42) matches only the number 42, so the match stops being exhaustive.
Question 20
What does #[derive(Debug)] do?
Answer. It lets you print it with {:?}.
Error Handling and File I/O (Lecture 13)
Key Concepts
Result<T, E>: HasOk(value)andErr(error), for when something failed and you can say why- Choosing between
Option,Result, andpanic!: nothing is a normal answer, it failed and here is why, or carrying on makes no sense panic!vsResult: Panic when unrecoverable, Result when recoverable- Error propagation: Passing errors up with
matchor? unwrap()andexpect(): Quick ways to extract values (but they can panic!)- The
?operator: Shortcut for "if error, return it; if ok, give me the value". The error type has to match the one your function returns, or be convertible into it
What's Not Important
- Custom error types, or implementing
std::error::Error Box<dyn Error>, and anything else that comes after the midterm- Writing file I/O from memory. You do not need to recall
fs::read_to_stringorfs::writeexactly, and you can look them up. You should be able to read them and say what you have to do with theResulteach one hands back
Quick Questions: Error Handling
Question 21
Option, Result, or panic!? One for each:
- a) looking up a name that is not in the list
- b) reading a file that is not there
- c) a situation your own code should have made impossible
And when is writing .unwrap() a reasonable thing to do?
Answer. a) Option, since "not in the list" is a normal answer. b) Result, since it failed and you can say why. c) panic!, since carrying on makes no sense.
.unwrap() is reasonable in a test, in a quick script, or when you can show the failure cannot happen.
Question 22
Why won't this code compile?
#![allow(unused)] fn main() { fn parse_number(s: &str) -> Result<i32, String> { let num = s.parse::<i32>()?; // parse() returns Result<i32, ParseIntError> Ok(num * 2) } }
- A) The
?operator can't be used inletstatements - B) You can't multiply by 2 inside
Ok() - C) The error types don't match:
ParseIntErrorvsString - D)
Okdoesn't match theResulttype
Answer. C. ? tries to turn the ParseIntError into a String, and no such conversion exists.
Putting It All Together
What You've Accomplished
In just a few weeks, you've learned:
- Professional development tools (shell, git, github, cargo)
- The foundations of a systems programming language
- Sophisticated pattern matching and error handling techniques
That's a lot.
And if it doesn't feel fluent yet, give it some time. It's like you memorized your first 500 words in a new spoken language but haven't had much practice actually speaking it yet. It feels awkward, and that's normal.
Midterm Strategy
- Focus on concepts: Understand the "why" behind the syntax and it will be easier to remember
- Practice with your hands: Literally and figuratively - practice solving problems, and practice on paper
- Take big problems step-by-step: Understand each line of code before reading the next. And make a plan before you start to hand-code
- Use the whole test: For hand-coding, it will help to look at code snippets from the rest of the test to remind you of syntax, that's not cheating!
Questions and Discussion
What is still unclear?
Activity time
See Activity 15. Two hand-coding problems, in groups of three.
(You said more hand-coding and more group work!)
One sheet per group, and a different person holds the pen for each problem. The other two say what to write and catch the mistakes.
Lecture 17 - The stack: frames and why it's fast
Announcements
Where does "undo" live?
How does your computer know what to undo? And why, if you keep hitting it, does it eventually stop?
Answer.
Every edit gets pushed onto a pile. Undo takes the top one off.
The most recent thing you did is the first thing to come back.
The pile has a fixed size, so old edits fall off the bottom.
That pile is called a stack, and today we'll see your program has one too.
Why we are about to spend three weeks on memory
Let me tell you some stories.
Heartbleed, 2014. A read past the end of a buffer, in security software. Leaked passwords, private keys, and personal data from roughly 17% of the world's secure web servers.
WannaCry, 2017
A buffer overflow in a Windows networking protocol. 200,000+ computers in 150 countries, including hospitals in the UK, about $4 billion in damages.
Still happening
Zoom, 2026. A use-after-free in the annotation tool let one meeting participant run code on another's computer. Patched this year.
In C and C++, roughly 70% of security vulnerabilities are memory safety bugs, according to both Microsoft and Google.
In safe Rust, none of these can happen. The use-after-free is a compiler error. The out-of-bounds reads stop the program on the spot, before anything leaks. A crash is a brief annoyance rather than a disaster.
Not every rewrite is about security
Dropbox, 2020. Their file-sync engine was written in Python. After years of bugs that were "extremely unlikely" but kept showing up anyway, they rewrote the whole engine in Rust, and the compiler now rules out whole classes of those bugs.
The rules that stop the security bug also stop the ordinary ones.
So here is the deal
For the next three weeks, Rust is going to tell you "no" a lot.
Every one of those refusals is one of these bugs, turned into a compiler error. You are going to learn the rules, and you are going to learn what each rule is for.
We start today with where your data actually is.
Learning Objectives
By the end of today, you should be able to:
- Explain the difference between RAM and storage, and say which one "memory" means
- Explain what a memory address is
- Name three approaches to memory management and one language that uses each
- Describe what a stack frame holds and when it appears and disappears
- Explain what a stack overflow is and what causes one
What is computer memory?
Think of your computer's memory like a giant filing cabinet.
- Each drawer holds one piece of information
- Each drawer has a unique number (an address)
- Your program can put things in drawers and take things out
What's the difference between RAM and storage (hard drive)?
RAM (Random Access Memory)
- Where your program's data lives while it is running
- Fast
- Temporary: gone when you close the program or power off
- This is why restarting your machine solves 50% of problems!
- Usually a few to a few dozen gigabytes
Storage (SSD or hard drive)
- Where your files live
- Much slower to read, several orders of magnitude
- Permanent: survives a reboot
- Usually hundreds of gigabytes or terabytes
When we say "memory" in this course, we mean RAM.
Which of these is RAM?
A helpful metaphor for RAM
Picture a very long street with billions of houses on it, numbered from 0.
- Every house is exactly the same size: one byte, which is 8 bits
- Every house has exactly one number and it's unique to that house
- To read or write anything, you need the number
That number is an address.
How big is a byte? Big enough for one u8 (0 to 255), or one i8 (-128 to 127), or one bool (which only needs one bit but gets a whole byte anyway, because a byte is the smallest thing the machine can address).
An i32 needs 4 bytes, so it fills four houses in a row.
Memory Addresses - Like Street Addresses
Let's look at some real ones.
fn main() { let x1: u8 = 10; let x2: u32 = 20; let x3: u32 = 30; // {:p} prints in address form. The p is for "pointer". // &x asks Rust for the address of x. println!("address of x1 {:p}", &x1); println!("address of x2 {:p}", &x2); println!("address of x3 {:p}", &x3); }
Rust prints addresses in hexadecimal, because they get very large.
Three things to notice. Look at the output, not at the slide.
- The addresses are in order: x1, then x2, then x3
- x2 is one byte past x1, because x1 is a
u8, which is one byte - x3 is four bytes past x2, because x2 is a
u32, which is four bytes
The variables were laid down one after another, each taking exactly as much room as its type needs.
How Memory is Organized - The Big Picture
Your program does not get the whole street. It gets a few neighborhoods, and they are used for different things.
Today: the stack. Wednesday: the heap.
The Stack: Like a literal stack of plates
The idea: Last thing you put on, first thing you take off
fn main() { // Stack: [ ] let x = 42; // Stack: [x=42 ] let y = true; // Stack: [x=42, y=true] println!("{}", x); } // Stack: [ ] ← Everything cleaned up automatically!
Stack characteristics:
- Super fast - just "put on top" or "take off top"
- Limited size - like a small tower of plates
- Automatic cleanup - when a function ends, its "plates" are removed
- Size must be known - each "plate" is a fixed size
Most Rust data you've seen lives on the stack: i32, bool, char, arrays, tuples
This one's worth saying again...
Size must be known, at compile time.
The stack works because everything is laid down in order with no gaps. To put x2 right after x1, the compiler has to know how big x1 is before the program runs.
So what cannot go on the stack? Anything that can grow.
- A
Stringyou push characters onto. - A
Vecyou push elements onto. - A file you read in, whose length you do not know until you read it
Those belong in tomorrow's lecture.
Stack Frames: Organized Sections
Each function call gets its own organized section called a stack frame
Stack frame holds all the data for one function call:
- Function parameters
- Local variables
- Return address (where to go back when function ends)
- Other bookkeeping info
Stack Memory:
┌─────────────────┐ ← Top of stack
│ Function B │ ← Stack frame for Function B (called by A)
│ parameters │
│ local vars │
├─────────────────┤
│ Function A │ ← Stack frame for Function A (main)
│ parameters │
│ local vars │
│ return info │
└─────────────────┘ ← Bottom of stack
When a function returns, its whole frame is thrown away at once. Nobody has to walk through it and clean up. The top of the stack just moves back down.
That is why the stack is fast.
Activity 17, Problem 1: your first stack
See Problem 1 on Activity 17.
┌──────────────────────────┐
│ add_one │
│ n: i32 = 1 │
│ result: i32 = 2 │
└──────────────────────────┘
┌──────────────────────────┐
│ main │
│ a: i32 = 1 │
│ b: i32 = ??? │
└──────────────────────────┘
Two frames. b is ??? because add_one has not returned yet. When it does, its frame disappears and 2 is copied into b.
Draw this out! You will be asked to draw one on the next midterm, and the more you practice as we go the more comfortable you'll be then.
A scope inside a function: shadowing
A { } block gets a mini-frame: a dashed box stacked on top of its function's frame. It pops off at the closing brace, taking its variables with it.
To find a variable, read from the top down, and stop at a solid line.
fn main() { let x = 5; println!("before: {}", x); { let x = 7; // DRAW HERE println!("inside: {}", x); } println!("after: {}", x); }
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ x: i32 = 7 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ x: i32 = 5 │
└──────────────────────────┘
let makes a second x in the mini-frame. Reading from the top, println! finds that one first. At the brace the mini-frame pops off, and the x on top is main's 5 again.
A scope inside a function: mut
Same program, but mut on the outside and no let on the inside.
fn main() { let mut x = 5; println!("before: {}", x); { x = 7; // DRAW HERE println!("inside: {}", x); } println!("after: {}", x); }
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ (nothing new) ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ x: i32 = 7 (was 5) │
└──────────────────────────┘
No let, so the mini-frame has no x. Reading down, x = 7 falls through the dashed line and writes into main's x, which is still there after the brace.
Activity 17, Problem 2: a scope inside a function
See Problem 2 on Activity 17.
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ bonus: i32 = 5 ╎
╎ doubled: i32 = 20 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
┌──────────────────────────┐
│ main │
│ total: i32 = 20 │
│ (was 10) │
└──────────────────────────┘
There is no let on the total line, so the mini-frame gets no total of its own. After the brace, only total is left, and it is still 20.
Stack Overflow - A Real Problem!
The stack has a fixed size, usually a few megabytes. Two ways to run out of space.
Way 1: too many frames.
fn count_forever(n: u64) -> u64 { count_forever(n + 1) // never returns, so the frame never goes away } fn main() { println!("{}", count_forever(0)); }
Every call adds a frame. Nothing ever returns. The stack grows until it hits its limit and the program dies.
Yes, the website is named after this! It is a very common way programs dies in languages that let you recurse.
Way 2: one frame that is too big.
fn main() { let small = [0u8; 1000]; // fine // let huge = [0u8; 10_000_000]; // 10 MB in one frame: crash }
Tomorrow you will learn the fix for way 2, which is to put the big thing somewhere else.
Three Approaches to Memory Management
Different programming languages handle memory differently:
-
Manual (C/C++): "You figure it out!"
- Programmer manually asks for memory and gives it back (C:
malloc/free) - Super fast, but easy to make dangerous mistakes
- Programmer manually asks for memory and gives it back (C:
-
Garbage Collection (Python/Java): "I'll handle it automatically!"
- Language automatically cleans up unused memory
- Safe but can cause random slowdowns
-
Ownership (Rust): "I'll help you get it right!"
- Compiler enforces rules to prevent mistakes
- Fast AND safe
This is why Rust can seem picky sometimes - it's preventing memory bugs!
The same three, as a spectrum
Control/Performance <----------------------------> Safety/Ease
C/C++ Rust Java/Go Python
│ │ │ │
Manual Ownership Garbage Garbage
Memory System Collection Collection
(pauses at (mostly frees
unpredictable things the moment
times) they are unused)
│ │ │ │
Fast, Unsafe Fast, Safe Slower, Safe Slowest, Safe
Rust's claim is that it broke the trade-off - this part of the course looks at Rust's "ownership system" to see how the magic happens.
Take-aways
- Memory is a numbered strip of one-byte cells, and an address is a cell number
- Your program's data lives in a few regions; today's is the stack
- Each function call gets a stack frame, thrown away whole when the function returns
- The stack is fast because it is ordered and automatic
- It is ordered and automatic because every size is known ahead of time
Tomorrow: what happens when the size is not known ahead of time.
Activity 17, Problems 3 and 4
Finish the last two problems on your sheet, and hand it in on your way out.
See activities/activity_17.md.
Lecture 18 - The heap: allocation, and why it is slower
Announcements
How much room for a name?
Your program is going to ask the user for their name and store it.
How many bytes should the compiler set aside?
You cannot know. Not "it is hard to know". The compiler runs before the user is even at the keyboard.
Yesterday we said the stack works because every size is known at compile time. So the name cannot go on the stack. Today: where it goes instead.
Where we left off
The stack is fast, ordered, and automatic, and it is all three for one reason: every size is known at compile time.
Which leaves an obvious problem. String and Vec can grow. So how have they been working this whole time?
Learning Objectives
By the end of today, you should be able to:
- Explain why dynamically sized data cannot live on the stack
- Name the three parts of a
Stringand say which part is on the heap - Compare the stack and the heap on speed, size, and cleanup
- Draw the stack and the heap at a given point in a program, with types labeled
- Explain why adding up a
Vec<Vec<i32>>by rows is faster than by columns
A demo that should not work
fn main() { let x1: i8 = 10; let mut s1: String = String::from("hello"); let x2: i8 = 20; println!("address of s1 {:p}, size of s1 {}", &s1, size_of::<String>()); println!("{s1}"); s1.push_str(" everyone!"); println!("address of s1 {:p}, size of s1 {}", &s1, size_of::<String>()); println!("{s1}"); }
Look at the output.
- The string got longer. It prints
hello everyone! - The address of
s1did not change - The size of
s1did not change. Still 24 bytes
How can the string be longer if s1 is the same size, in the same place?
Because s1 is not the string.
What a String actually is
Three fields, 24 bytes total, sitting on the stack:
ptr, 8 bytes: the address where the characters arelen, 8 bytes: how many characters there are right nowcap, 8 bytes: how many there is room for
Stack: Heap:
┌─────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ s1: String │ │ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ──────┼─────────▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└─────────────┘
The characters are somewhere else entirely. push_str changed len, and changed what is at the far end of that arrow. It never touched the 24 bytes on the stack.
This is the shape of every growable type in Rust. Vec, HashMap, HashSet: a small fixed-size handle on the stack, pointing at data that can change size somewhere else.
The heap - library analogy
- The card is on the stack: small, every card the same size, and it tells you where to go
- The book is on the heap: any size, shelved wherever there was room
Yes, librarians call the shelves "the stacks." In this picture they are the heap. Sorry.
If a storage unit works better for you: the key in your pocket is on the stack, the unit across town is the heap.
Remember Customer?
#![allow(unused)] fn main() { enum State { NY, MA, CA } struct Customer { name: String, age: u32, state: State, member: bool, } let alice = Customer { name: "Alice Smith".to_string(), age: 25, state: State::NY, member: true, }; }
Customer in memory
Stack: Heap:
┌────────────────────────┐ ┌───────────────┐
│ alice: Customer │ ┌──▶│ "Alice Smith" │
│ ├ name: String │ │ └───────────────┘
│ │ ptr ───────────────┼──────┘
│ │ len: 11 │
│ │ cap: 11 │
│ ├ age: u32 = 25 │
│ ├ state: State = NY │
│ └ member: bool = true │
└────────────────────────┘
The struct is a fixed size, so it sits on the stack. name is a handle, pointing at its text on the heap. age, state, and member are a fixed size, so they sit right in the struct.
An enum is a fixed size too. Rust stores which variant it is as a small number, NY as 0, MA as 1, CA as 2. One byte, on the stack.
Who cleans up the heap?
- The stack cleans itself up: a frame goes away when the function returns, automatically, with no code.
- The heap does not. Somebody has to say "I am done with this, take it back."
Who does it?
- In C, that somebody is you, and forgetting is a bug.
- In Python, a garbage collector figures it out at run time.
- In Rust, it is the compiler, using a set of rules.
That set of rules is called ownership, and it is the next two weeks.
Stack vs. Heap
| Stack 🍽️ | Heap 📦 |
|---|---|
| Fixed size, known at compile time | Variable size, can grow/shrink |
| Super fast access | Slower access (follow pointer) |
| Automatic cleanup | Manual management needed |
| Limited space | Lots of space |
i32, bool, arrays, tuples | String, Vec, HashMap, etc. |
Don't memorize this table. Every row follows from "the stack keeps things in order and the heap does not." Reason it out, then check yourself against the table.
Think-pair-share: stack or heap?
Your program has to store each of these. Is it small and a fixed size, or could it grow or be big? Write S or H next to each.
- A person's zip code
- A person's street address
- A website's URL
- The barcode on a cereal box
- Whether it is raining right now
- A playlist
- The temperature outside
- A photo from your phone
- A post, capped at 280 characters
- A US state
Stack: 1, 4, 5, 7, 10. Heap: 2, 3, 6, 8. Either: 9. But there's also some subjectivity here.
Why is the heap slower? Remember this?
From Lecture 9: two ways to add up every number in a 10,000 by 10,000 grid.
// Across each row, then down to the next row
for r in 0..rows {
for c in 0..cols {
sum = sum + matrix[r][c];
}
}
// Down each column, then over to the next column
for c in 0..cols {
for r in 0..rows {
sum = sum + matrix[r][c];
}
}
Same 100 million additions. Same Big O. Going down the columns is about 6x slower.
What a Vec<Vec<i32>> looks like
matrix is a Vec of rows, and every row is its own Vec.
Stack: Heap:
┌─────────────────────┐ ┌────────────────┐ ┌───┬───┬───┐
│ grid: Vec<Vec<i32>> │ ┌─▶│ ptr ───────────┼───────▶│ 1 │ 2 │ 3 │
│ ptr ──────────────┼───┘ │ len: 3, cap: 3 │ └───┴───┴───┘
│ len: 3 │ ├────────────────┤ ┌───┬───┬───┐
│ cap: 3 │ │ ptr ───────────┼───────▶│ 4 │ 5 │ 6 │
└─────────────────────┘ │ len: 3, cap: 3 │ └───┴───┴───┘
├────────────────┤ ┌───┬───┬───┐
│ ptr ───────────┼───────▶│ 7 │ 8 │ 9 │
│ len: 3, cap: 3 │ └───┴───┴───┘
└────────────────┘
Each row is its own block on the heap, wherever there was room. Nothing says row 1 comes right after row 0.
Let's check
fn main() { let grid: Vec<Vec<i32>> = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]; println!("grid[0][0] {:p}", &grid[0][0]); println!("grid[0][1] {:p}", &grid[0][1]); println!("grid[0][2] {:p}", &grid[0][2]); println!("grid[1][0] {:p}", &grid[1][0]); println!("grid[2][0] {:p}", &grid[2][0]); }
Across a row, the addresses go up by 4, one i32 at a time. The next row starts somewhere else entirely.
The CPU reads memory in chunks
Going out to RAM is slow, compared to everything else the CPU does. So when it needs one number, it does not fetch one number. It fetches the whole chunk around it, 64 bytes on most chips and 128 on my laptop, and keeps it in a small, very fast memory on the chip called the cache.
The library version: you walk to the stacks for one book, and can easily see the whole shelf.
If the next thing you need is on that shelf, it is nearly free.
Across vs. down
Across a row: one trip [ # # # # # # # # ... ] use all of it
Down a column: one trip [ # . . . . . . . ... ] use one number
one trip [ # . . . . . . . ... ] use one number
one trip [ # . . . . . . . ... ] use one number
# is a number you use. Across a row, the next number is a neighbor, already in the chunk. Down a column, every step is a different row, so a different block, so another trip, and you use one number out of each chunk.
So why is the heap slower?
- Getting space is slower. The stack adds to the top. The heap has to hunt for a gap big enough
- Reading it can be slower. Data spread across many blocks means many trips
Activity 18, Problem 1: an array, a Vec, and a String
See Problem 1 on Activity 18.
Stack: Heap:
┌────────────────────────────┐
│ main │
│ a: [i32; 3] = [1, 2, 3] │
│ v: Vec<i32> │ ┌───┬───┬───┐
│ ptr ───────────────────┼───────▶│ 1 │ 2 │ 3 │
│ len: 3, cap: 3 │ └───┴───┴───┘
│ s: String │ ┌─────┬─────┐
│ ptr ───────────────────┼───────▶│ 'h' │ 'i' │
│ len: 2, cap: 2 │ └─────┴─────┘
└────────────────────────────┘
a and v print the same thing but live in different places. An array's size is part of its type, so it fits in the frame. A Vec can grow, so its values go on the heap.
String vs &str - Finally Explained!
We can explain this a bit more now with stack/heap:
String: Owned Text on the Heap
#![allow(unused)] fn main() { let name = "Alice".to_string(); // or String::from("Alice") }
What happens in memory:
Stack: Heap:
┌──────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ name: String │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ ptr ───────┼────────▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└──────────────┘
- String = the metadata on the stack (pointer, length, capacity)
- Actual text = lives on the heap
- You own it = you can modify it, and Rust will clean it up for you
&str: Borrowed Text (Points to Existing Data)
#![allow(unused)] fn main() { let greeting = "Hello"; // This is &str }
What happens in memory:
Stack: (Heap) Program Binary (Text Section):
┌────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ greeting: &str │ │ 'H' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ─────────┼───────────────────────────▶│ │ │ │ │ │
│ └ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
└────────────────┘
- &str = just a pointer and length on the stack
- Actual text = lives in your compiled program
- You're borrowing it = you can read it, but you can't edit it
Two fields, not three. There is no cap because a &str can't grow, it's fixed-size. In a sense, its cap is always its len, which would be redundant to track separately.
Activity 18, Problem 2: a String and a string literal
See Problem 2 on Activity 18.
Stack:
┌──────────────────────────┐
│ print_label │ Program binary:
│ label: &str │ ┌─────┬─────┬─────┐
│ ptr ─────────────────┼───────▶│ 'A' │ 'g' │ 'e' │
│ len: 3 │ └─────┴─────┴─────┘
│ value: i32 = 5 │
└──────────────────────────┘
┌──────────────────────────┐
│ main │ Heap:
│ name: String │ ┌─────┬─────┬─────┐
│ ptr ─────────────────┼───────▶│ 'B' │ 'o' │ 'b' │
│ len: 3, cap: 3 │ └─────┴─────┴─────┘
│ age: i32 = 5 │
└──────────────────────────┘
The String's text is on the heap because it could grow. The literal "Age" was written into the program when it was compiled, so label points into the program itself.
Let's Watch the Stack in Action!
Here's an example showing how the stack builds up and comes down as functions are called.
The diagrams will be online after class but there's space on your paper to draw them yourselves as we go.
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Steps 1 to 4. Draw it once, then keep updating it as we go: add each frame when it is called, cross it out when it is gone.
Step 1: main() starts
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ main() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ x: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ name: &str │ ▲
│ │ ptr ─────────────────────┼─────────┘
│ │ len: 5 │
│ └ result: String = ??? │ Heap: (nothing yet)
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 2: Call process_data(x, name)
Function arguments and local variable doubled are added to the stack:
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 84 │ │
│ └ greeting: String = ??? │ │
├──────────────────────────────┤ │ Heap: (nothing yet)
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 3: Enter the bracketed scope {}
The scope creates its own mini-stack frame with temporary variables:
Stack:
┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
╎ { scope } ╎
╎ ├ temp_multiplier: i32 = 10 ╎
╎ └ temp_result: i32 = 840 ╎
└╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘ Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 85 │ <- was 84 │
│ └ greeting: String = ??? │ │
├──────────────────────────────┤ │ Heap: (nothing yet)
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 4: Exit the bracketed scope
The mini-frame is gone, and temp_multiplier and temp_result with it. doubled keeps its new value:
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 85 │ │
│ └ greeting: String = ??? │ │
├──────────────────────────────┤ │ Heap: (nothing yet)
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 5: greeting is built
format! makes a new String, with its text on the heap. The first heap allocation in this whole program.
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ process_data() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ num: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ text: &str │ ▲ ▲
│ │ ptr ─────────────────────┼─────────┘ │
│ │ len: 5 │ │
│ ├ doubled: i32 = 85 │ Heap: │
│ └ greeting: String │ ┌────────────────────┐ │
│ ptr ─────────────────────┼──────────▶│ "Hello Alice, your │ │
│ len: 30 │ │ number is 85" │ │
│ cap: 46 │ └────────────────────┘ │
├──────────────────────────────┤ │
│ main() │ │
│ ├ x: i32 = 42 │ │
│ ├ name: &str │ │
│ │ ptr ─────────────────────┼───────────────────────────────────┘
│ │ len: 5 │
│ └ result: String = ??? │
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Steps 5 to 7. Start a fresh drawing here, from the moment greeting is built. Same rule: update it, do not redraw it.
Step 6: process_data() returns
process_data's frame is gone, greeting with it. The text it pointed at is still on the heap, and now result points at it:
Stack: Program binary:
┌──────────────────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ main() │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ x: i32 = 42 │ └─────┴─────┴─────┴─────┴─────┘
│ ├ name: &str │ ▲
│ │ ptr ─────────────────────┼─────────┘
│ │ len: 5 │ Heap:
│ └ result: String │ ┌────────────────────┐
│ ptr ─────────────────────┼──────────▶│ "Hello Alice, your │
│ len: 30 │ │ number is 85" │
│ cap: 46 │ └────────────────────┘
└──────────────────────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Step 7: main() ends
All stack data is cleaned up, and Rust automatically frees the heap data:
Stack: Heap:
┌─────────┐ ┌─────────────┐
│ (empty) │ │ (cleaned up │
└─────────┘ │ by Rust!) │
└─────────────┘
fn main() { let x = 42; // Stack variable let name = "Alice"; // Points into the program let result = process_data(x, name); println!("{}", result); } fn process_data(num: i32, text: &str) -> String { let mut doubled = num * 2; // Stack variable // A bracketed scope creates its own mini-stack frame! { let temp_multiplier = 10; // New scope variable let temp_result = doubled * temp_multiplier; // Another scope variable println!("Temp calculation: {}", temp_result); doubled = doubled + 1; // Modify outer variable } // temp_multiplier and temp_result are destroyed here! let greeting = format!("Hello {}, your number is {}", text, doubled); greeting // Return String (heap data) }
Take-aways from this example
- Stack builds up as functions are called, shrinks as they return
- Bracketed scopes
{}create mini-stack frames within functions - Variables in scopes are destroyed when the scope ends, changes to outer variables persist
- Heap data can outlive the function that created it, when the function returns it
- Rust automatically cleans up heap data when no one owns it anymore
Activity 18, Problem 3
Finish Problem 3 on your sheet, and Problem 4 if you have time. Hand it in on your way out.
See activities/activity_18.md.
Lecture 19 - Pointers: &, * , and unsafe
Announcements
A shortcut to a 4 GB video
You make a desktop shortcut (an "alias" on a Mac) to a 4 GB video. The shortcut itself is a few kilobytes.
Where is the video?
Where it was originally. The shortcut just gives directions for where to find the video, and if you delete the video the directions are still there, just invalid.
A value that holds where to find something is a called pointer.
Where we left off
Tuesday we printed addresses: &x asks for the address of x, and {:p} prints it. The p was for pointer.
Wednesday we drew a lot of arrows like this:
Stack: Heap:
┌─────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ s1: String │ │ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ──────┼─────────▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└─────────────┘
Every arrow we drew was a pointer: a value that holds an address.
Learning objectives
By the end of class today you should be able to:
- Explain how a pointer, a reference, and a
String'sptrfield are the same idea - Read the type
*const i32out loud and say what it holds - Explain what dereferencing does, and why Rust makes you write
unsafeto do it - Draw a reference in a stack and heap diagram, and say where its arrow ends
That arrow, printed
fn main() { let x: i32 = 7; let s = String::from("hello"); println!("address of x {:p}", &x); println!("address of s (handle) {:p}", &s); println!("s's ptr (text) {:p}", s.as_ptr()); println!("s's len {}", s.len()); println!("s's cap {}", s.capacity()); }
s.as_ptr(), s.len(), and s.capacity() hand you the three fields from Wednesday's diagram. ptr is the address at the tip of the arrow.
What do you notice?
x and s are neighbors on the stack. The text is somewhere else entirely. The arrow from the stack to the heap is just that second number.
A pointer is a variable that holds an address
fn main() { let x1: i32 = 10; // Turns a reference into a raw pointer. You will read this, not write it let ptr_x1: *const i32 = &x1 as *const i32; println!("address of x1 {:p}", &x1); println!("size of x1 {}", size_of::<i32>()); println!("ptr_x1 points to {:p}", ptr_x1); println!("size of ptr_x1 {}", size_of::<*const i32>()); }
So ptr_x1 does not contain an i32, it contains an address to an i32.
Two things to notice in the output:
- The address inside
ptr_x1is the address ofx1 ptr_x1is 8 bytes, the size of an address on this machine. Ani32is 4
Both variables are fixed size, so both live on the stack. x1 is 4 bytes holding 10. ptr_x1 is 8 bytes holding an address, the same size as the ptr field in a String.
Stack:
┌──────────────────────────────┐
│ main() │
│ ├ x1: i32 = 10 │◀─┐
│ └ ptr_x1: *const i32 ────────┼──┘
└──────────────────────────────┘
New today: pointers can go from the stack back to the stack too!
Dereferencing: follow the address
fn main() { let x1: i32 = 10; let ptr_x1: *const i32 = &x1 as *const i32; unsafe { println!("{}", *ptr_x1); } }
*ptr_x1 means follow the address in ptr_x1 and look at what is there.
Why did that need unsafe?
Dereferencing (raw pointers) is dangerous!
Nothing guarantees that the address:
- is a valid address at all
- holds a value of the type you think
- has been initialized
- has not been changed or freed by some other part of the program
So Rust makes you swear you know what you're doing. It's like signing a waiver before you jump out of an airplane - it says you are taking responsibility for this one.
A pointer is not a copy
fn main() { let mut x1: i32 = 10; let ptr_x1: *const i32 = &x1 as *const i32; x1 = 30; unsafe { println!("{}", *ptr_x1); } }
What does this print?
30. The pointer holds an address. Change what is at the address and what the pointer sees changes.
You can write through a pointer too
fn main() { let mut x1: i32 = 10; // Same conversion, for a pointer you can write through let ptr_x1: *mut i32 = &mut x1 as *mut i32; unsafe { *ptr_x1 = 50; } println!("{x1}"); }
*mut i32 instead of *const i32. Now dereferencing gives you something you can assign to.
There's is a lot of new syntax today! While you'll need to write unsafe rust in the project, and will read some on the exam, you won't need to hand-code it or remember the syntax details perfectly. Everyday Rust uses & and *, and soon our focus will just be on using those well.
References: a pointer with rules
Typically, we don't really writte let ptr_x1: *mut i32 = &mut x1 as *mut i32;... we just make a "reference":
fn main() { let x1: i32 = 10; let ref_x1: &i32 = &x1; println!("address of x1 {:p}", &x1); println!("ref_x1 refers to {:p}", ref_x1); println!("ref_x1's value is {}", ref_x1); }
A reference is a pointer. Same 8 bytes, same address inside.
Two differences from "bare" pointers:
- We didn't need
unsafe. I wonder why... - No
*to read it. Dereferencing can sometimes be inferred in Rust, like types.
Read-only and read-write references
References come in two flavors:
&T, an immutable reference: read-only (like&self)&mut T, a mutable reference: read and write (like&mut self)
fn main() { let mut x1: i32 = 10; let r: &mut i32 = &mut x1; *r += 1; println!("x1 is now {}", x1); }
So the type of r here is &mut i32 (if it were an immutable ref its type would be &i32)
That *r is the same dereference operator from before, but this time we can trust it (we don't need unsafe!).
Activity 19, Problem 1: draw the arrows
See Problem 1 on Activity 19.
Stack:
┌────────────────────┐
│ main() │
│ ├ x: i32 = 15 │◀──┐
│ ├ y: i32 = 20 │◀┐ │
│ ├ r1: &i32 ────────┼─┘ │
│ └ r2: &mut i32 ────┼───┘
└────────────────────┘
x is 15, not 10: *r2 = 15 followed the arrow and wrote into x. Both arrows end in the stack, and nothing is on the heap.
Within a frame you can write bottom-up or top-down, it doesn't matter.
Where can an arrow point?
fn main() { let x: i32 = 7; let v = vec![10, 20, 30]; let label: &str = "scores"; let r_x: &i32 = &x; let r_20: &i32 = &v[1]; println!("r_x points to {:p}", r_x); println!("r_20 points to {:p}", r_20); println!("label points to {:p}", label); }
Which one points into the stack?
r_x. Its address is nowhere near the other two. r_20 points into the heap, and label points into the program itself.
Look at what printed for label: metadata: 6. That's the length. A &str is a pointer plus a length, called a fat pointer. More on those in the strings lecture.
Three places an arrow can end
Stack: Heap: Program:
┌──────────────────────────┐
│ main() │
│ ├ x: i32 = 7 │◀─┐
│ ├ v: Vec<i32> │ │ ┌────┬────┬────┐
│ │ ├ ptr ────────────────┼──┼──────▶│ 10 │ 20 │ 30 │
│ │ ├ len: 3 │ │ └────┴────┴────┘
│ │ └ cap: 3 │ │ ▲
│ ├ label: &str │ │ │ ┌──────────┐
│ │ ├ ptr ────────────────┼──┼──────────────┼────────▶│ "scores" │
│ │ └ len: 6 │ │ │ └──────────┘
│ ├ r_x: &i32 ─────────────┼──┘ │
│ └ r_20: &i32 ────────────┼─────────────────┘
└──────────────────────────┘
- Into the stack:
&x - Into the heap:
&v[1]points straight at the 20, not atv - Into the program: a string literal
r_x and r_20 are both &i32. The type does not tell you where the arrow ends.
The handle, or the element?
Same v as before. &v[1] pointed at the 20. What does &v point at?
fn main() { let v = vec![10, 20, 30]; let whole: &Vec<i32> = &v; let first: &i32 = &v[0]; println!("address of v {:p}", &v); println!("v's ptr {:p}", v.as_ptr()); println!("v's len {}", v.len()); println!("whole points to {:p}", whole); println!("first points to {:p}", first); }
Which addresses match?
whole matches the address of v: it points at the handle, on the stack. first matches v's ptr field: it points at the first element, on the heap.
&v points at the handle
Stack: Heap:
┌──────────────────────────┐
│ main() │
┌─▶│ ├ v: Vec<i32> │ ┌────┬────┬────┐
│ │ │ ├ ptr ────────────────┼───────▶│ 10 │ 20 │ 30 │
│ │ │ ├ len: 3 │ └────┴────┴────┘
│ │ │ └ cap: 3 │ ▲
└──┼── whole: &Vec<i32> │ │
│ └ first: &i32 ───────────┼──────────┘
└──────────────────────────┘
whole: &Vec<i32>is an arrow to the handle:vitself, three fields on the stackfirst: &i32is an arrow to the first element, the same addressv's ownptrholds
This is the arrow everyone draws wrong. Asked to draw &v, most people run the arrow straight to the numbers. A reference points at the thing you put the & in front of, and here that is v, the handle.
Activity 19, Problem 2: four arrows
See Problem 2 on Activity 19.
Stack: Heap:
┌──────────────────────────┐
│ main() │
│ ├ numbers: Vec<i32> │◀──┐ ┌────┬────┬────┬────┐
│ │ ├ ptr ────────────────┼───┼───────▶│ 10 │ 20 │ 30 │ 40 │
│ │ ├ len: 4 │ │ └────┴────┴────┴────┘
│ │ └ cap: 4 │ │ ▲
│ ├ name: String │◀┐ │ │ ┌─────┬─────┬─────┬─────┬─────┐
│ │ ├ ptr ────────────────┼─┼─┼───────────────┼───▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │ ├ len: 5 │ │ │ │ └─────┴─────┴─────┴─────┴─────┘
│ │ └ cap: 5 │ │ │ │
│ ├ r1: &Vec<i32> ─────────┼─┼─┘ │
│ ├ r2: &i32 ──────────────┼─┼─────────────────┘
│ ├ r3: &String ───────────┼─┘
│ └ r4: &str │ Program binary:
│ ├ ptr ────────────────┼───────────▶┌───────┐
│ └ len: 3 │ │ "Bob" │
└──────────────────────────┘ └───────┘
Two of the four arrows end on the stack: r1 and r3, at the handles. r2 goes into the heap, at the 20, and r4 into the program.
An arrow into another frame
fn with_bonus(points: &i32) -> i32 { let result = *points + 5; result } fn main() { let score = 10; let total = with_bonus(&score); println!("{score} {total}"); }
What does this print?
10 15. with_bonus never sees score by name. It gets an arrow to it, follows the arrow to read the 10, and leaves score alone.
Drawn with Tuesday's frames
Stack:
┌──────────────────────────┐
│ with_bonus() │
│ ├ points: &i32 ──────────┼──┐
│ └ result: i32 = 15 │ │
├──────────────────────────┤ │
│ main() │ │
│ ├ score: i32 = 10 │◀─┘
│ └ total: i32 = ??? │
└──────────────────────────┘
points lives in with_bonus's frame and points down, into main's. *points follows the arrow and reads score where it lives. The only thing copied was 8 bytes of address.
When with_bonus returns, its frame is thrown away, arrow and all. The 15 in result is copied out into total first, the same as Tuesday's add_one. score stays behind, untouched.
Every &self method you have written works this way.
What if the arrow points the other way?
fn make_number() -> &i32 {
let x = 42;
&x
}
fn main() {
let r = make_number();
println!("{}", r);
}
Stack:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ make_number() (gone) ░
░ └ x: i32 = 42 ░◀─┐
░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │
┌──────────────────────────┐ │
│ main() │ │
│ └ r: &i32 ───────────────┼──┘
└──────────────────────────┘
make_number returns, and its frame is thrown away. The arrow is still there, pointing at memory that is no longer anybody's.
It is the shortcut to a deleted video. Rust refuses to compile this. C compiles it, with a warning at most.
Activity 19, Part 2: poke at pointers
Laptops out, one per pair. Open Activity 19 on the course website.
Run each experiment, change what it tells you to change, and write what you see on your sheet to turn in. (Just get as far as you can.)
Lecture 20 - Pointer danger: seven ways C loses your memory
Announcements
Where we left off
Friday: a pointer (and &) holds an address, and dereferencing (*) follows it.
To * a raw pointer we needed an unsafe block, which means we are taking responsibility.
Today: responsibility for what, exactly?
Learning objectives
By the end of today, you should be able to:
- Read a short program, in
unsafeRust or in C, that allocates and frees memory by hand, and say what each line does - Name seven ways a pointer can be wrong
- Explain what Rust does to avoid these issues
You will write some unsafe Rust in Project 2. On exams, you may need to read it, but hand-coding is safe Rust only.
Doing the heap by hand
A line we have written a few times:
let s = "hello".to_string();
Here is what it does under the hood:
fn main() { unsafe { // 1. ask the heap for five bytes let ptr: *mut u8 = libc::malloc(5) as *mut u8; // 2. put the letters in them std::ptr::write(ptr as *mut [u8; 5], *b"hello"); println!("letters at {:p}", ptr); } }
malloc(5) means "give me five bytes". It hands back a pointer to them.
This is core to checkpoint 2. libc::malloc is your project's MALLOC.malloc, same shape. Put size_of::<T>() * n where the 5 is and you have the line your push writes when it runs out of room.
That is the whole heap side of it.
What to_string does after step 2 is remember three numbers on the stack:
- where the letters are (
ptr) - how many there are (
len) - how much room there is (
cap)
Notice malloc does not know or care that you wanted letters when it decided what memory to take!
Allocated is not initialized
Between step 1 and step 2, what is in those five bytes?
Whatever was there before. malloc reserves space; it does not clear it.
You often get zeros, because allocators frequently hand out zeroed pages. You cannot rely on that, so if you try to read it, bad things can happen.
Writing before reading
So you have to write the value in before you read anything out. This time, a whole String handle on the heap, not just its letters:
fn main() { unsafe { let my_ptr: *mut String = libc::malloc(size_of::<String>()) as *mut String; std::ptr::write(my_ptr, String::from("hello!")); println!("{}", *my_ptr); } }
Three steps where you used to write one line: ask for bytes, put a value in them, then use it.
And you have to give it back
The stack cleans up after itself. The heap does not.
fn main() { unsafe { let my_ptr: *mut String = libc::malloc(size_of::<String>()) as *mut String; std::ptr::write(my_ptr, String::from("hello!")); println!("{}", *my_ptr); std::ptr::read(my_ptr); // frees the letters libc::free(my_ptr as *mut libc::c_void); // frees the handle } }
Why two lines to clean up one thing?
Two blocks, two frees
Stack: Heap:
┌───────────┐ the handle: 24 bytes, from your malloc
│ my_ptr ───┼──────▶┌──────────────┐
└───────────┘ │ ptr ─────────┼───▶ the letters: from String::from
│ len: 6 │ ┌───┬───┬───┬───┬───┬───┐
│ cap: 6 │ │ h │ e │ l │ l │ o │ ! │
└──────────────┘ └───┴───┴───┴───┴───┴───┘
Usually a String's handle sits on the stack. Here we put it on the heap ourselves, so there are two blocks, and each needs its own free.
libc::freefrees the handle, the block we asked forstd::ptr::readleads to the letters being freed
read is a misleading name. Reading a book doesn't destroy it, but ptr::read does: think of it as "read and destroy", so it frees the letters.
Without read the letters would stay on the heap forever. This is a leak inside a cleanup, the cause of many real-world bugs.
Why this matters
Three numbers from teams that maintain some of the biggest C and C++ codebases in the world:
- Microsoft, 2019: about 70% of the security bugs they fix each year are memory-safety bugs
- Chrome, 2020: about 70% of serious security bugs are memory-safety bugs. Half of those are use-after-free, bug 2 coming up
- Android, 2024: new code has been written in memory-safe languages, Rust among them, since 2019. Memory-safety bugs fell from 76% of Android's vulnerabilities to 24%
These are some of the best-funded engineering teams on earth, and they still make these mistakes in C and C++.
Enough C to read the bugs
Everything coming up is C. You need four things.
| C | What it is | Rust equivalent |
|---|---|---|
int* ptr | a pointer to an int | *mut i32 |
malloc(100) | ask for 100 bytes | libc::malloc(100) |
free(data) | give them back | libc::free(data) |
NULL | a pointer to nothing, address 0 | none in safe Rust |
The * in a type means "pointer to".
The * in an expression means "follow it".
Same two meanings as Rust.
Let's look at some bugs.
Bug 1: Memory leaks
What happens: never free it
// C code - compiles, runs, and quietly grows
void greet() {
char* name = malloc(100);
strcpy(name, "hello");
printf("%s", name);
} // No free(name): 100 bytes gone, every call
During greet(): After greet() returns:
┌──────────────┐ ░░░░░░░░░░░░░░░░
│ greet() │ ┌───────┐ ░ greet() gone ░ ┌───────┐
│ └ name ──────┼───▶│ hello │ ░░░░░░░░░░░░░░░░ │ hello │
└──────────────┘ └───────┘ └───────┘
Stack Heap ▲
no arrow left
When greet returns, name goes with its frame. The 100 bytes stay, and with no arrow left, nothing can ever free them.
Why it's dangerous:
- Nothing crashes. The program just keeps growing
- A server that runs for weeks eventually runs out of memory
- The bug is a line that isn't there
Rust: frees a value when its owner goes out of scope (more Wednesday). But this doesn't stop all leaks... (There was drama. People called it the "leakpocalypse". But you'll probably never run into it.)
Project 2: your FastVec lives in unsafe, where nothing frees for you. Checkpoint 3's Drop has you writing that free.
Bug 2: Use-after-free
What happens: free it, then use it anyway
// C code - compiles but UNSAFE!
char* data = malloc(100);
strcpy(data, "hello");
free(data); // Memory handed back to the allocator
// Later...
printf("%s", data); // Reading freed memory!
// Might work, might crash, might read garbage
Why it's dangerous:
- The memory may already belong to something else
- Can expose passwords, card numbers
- Works in testing, crashes in production
Rust: won't compile a use of a value after it is freed.
Bug 3: Double-free
What happens: free the same memory twice
// C code - compiles but CRASHES!
char* ptr1 = malloc(100);
char* ptr2 = ptr1; // Two pointers to same memory
free(ptr1); // Free once
free(ptr2); // Free again! CRASH or worse
Stack: Heap:
┌──────────────────┐
│ main() │
│ ├ ptr1 ──────────┼──┐ ┌───────────┐
│ └ ptr2 ──────────┼──┴───▶│ 100 bytes │
└──────────────────┘ └───────────┘
Two arrows, one block. After free(ptr1), ptr2 still holds the same address, so free(ptr2) hands back a block that is no longer yours.
Why it's dangerous:
- Corrupts the allocator's bookkeeping
- A known route to security exploits
Rust: one owner, so one free.
We can write this one in Rust too.
fn main() { unsafe { let ptr0: *mut i32 = libc::malloc(size_of::<i32>() * 2) as *mut i32; libc::free(ptr0 as *mut libc::c_void); libc::free(ptr0 as *mut libc::c_void); } }
Bug 4: Dangling pointers
What happens: a pointer outlives what it points to
// C code - compiles but UNSAFE!
int* get_number() {
int x = 42;
return &x; // Returning pointer to local variable!
} // x's frame is thrown away here
int main() {
int* ptr = get_number();
printf("%d", *ptr); // Reading a dead frame!
}
Draw the stack. What happens to get_number's frame at the closing brace?
Stack:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ get_number() (gone) ░
░ └ x: int = 42 ░◀─┐
░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │
┌──────────────────────────┐ │
│ main() │ │
│ └ ptr: int* ─────────────┼──┘
└──────────────────────────┘
It is thrown away. The address still looks fine, but it points into a frame that no longer exists, and the next function call writes over it.
Rust: a reference can't outlive its data. Friday's last slide.
Bug 5: Buffer overflow
What happens: writing past the end of an array
// C code - compiles but CRASHES!
int arr[5];
for (int i = 0; i <= 5; i++) { // Off by one!
arr[i] = i; // i = 5 writes past the end
}
[0] [1] [2] [3] [4] [5]
┌─────┬─────┬─────┬─────┬─────┐ ┌╌╌╌╌╌┐
│ 0 │ 1 │ 2 │ 3 │ 4 │ ╎ 5 ╎
└─────┴─────┴─────┴─────┴─────┘ └╌╌╌╌╌┘
└─────── arr, 5 ints ───────┘ someone else's
arr[5] lands in memory that belongs to something else, and C does not check.
Why it's dangerous:
- Overwrites whatever comes next, other variables included
- Can overwrite where the function returns to: a classic exploit
- Heartbleed (2014): the same bug while reading. Leaked servers' passwords and keys
Rust: checks every index, and panics instead.
Bug 6: Null pointers
What happens: following a pointer to nothing
// C code - compiles but CRASHES!
char* find_name(int id) {
if (id == 1) {
return "Alice";
}
return NULL; // "No name" is spelled NULL
}
int main() {
char* name = find_name(2);
printf("%c", name[0]); // Follows NULL. Crash
}
Stack:
┌──────────────────────────┐
│ main() │
│ └ name: char* = NULL ────┼──▶ address 0: nothing here
└──────────────────────────┘
NULL is address 0, and address 0 is never yours. Following it crashes the program.
Why it's dangerous:
- Any pointer might be
NULL mallocreturnsNULLwhen it fails. Easy to forget to check- Its inventor, Tony Hoare (1965), called it his "billion-dollar mistake"
Rust: a reference is never null! "Maybe nothing" is Option, and you must handle None. We've done this a lot now!
Bug 7: Data races
What happens: two threads, same memory, at least one writing
// C code with threads - compiles but RACE CONDITION!
int counter = 0;
void* increment(void* arg) {
for (int i = 0; i < 1000000; i++) {
counter++; // Not thread-safe!
}
}
// Run two threads...
// Expected: counter = 2,000,000
// Actual: counter = ??? (unpredictable!)
Why it's dangerous:
- A different answer every run
- Nearly impossible to reproduce
Rust: refuses to compile it. We'll fix it by the end of the term.
Memory safety: summary
| Bug Type | What It Is | How Rust Prevents |
|---|---|---|
| Leak | Never freeing | Ownership, mostly |
| Use-after-free | Using freed memory | Borrow checker |
| Double-free | Freeing twice | Ownership |
| Dangling pointer | Pointer outlives data | Lifetimes |
| Buffer overflow | Array out of bounds | Bounds checking |
| Null pointer | Following an address to nothing | Option |
| Data race | Concurrent unsynchronized access | (We'll see!) |
All of them caught at compile time, except bounds, which panics safely at run time, and leaks, which Rust only mostly prevents.
Look at the middle column - they're generally all mistakes about who is allowed to access what and when.
What Rust's protection costs:
- a bit of time (checking bounds)
- annoyance from a picky compiler
But it's worth it!
What we signed for when we use unsafe
Inside unsafe, all these bugs become possible again:
- Forget to
free: leak. (Project 2 checkpoint 3!) - Read through a pointer after
free: use-after-free freethe same pointer twice: double-free- Write past the end of what you asked
mallocfor: buffer overflow - Follow a null pointer: crash
You'll run into many of these in Project 2!
Write down why each unsafe block is OK. Rust programmers put a // SAFETY: comment above every one, like // SAFETY: p came from malloc, and i < len, to help keep track of what's happening and catch bugs!
Preview of ownership - Bugs happen when no one is responsible
In every memory bug there are several pointers to one piece of data, and no answer to a simple question:
a variable ───────────┐
▼
┌──────────┐
a list entry ───▶│ the data │◀─── another function
└──────────┘
Whose is it?
C has no answer.
Rust answers at compile time, by insisting there is exactly one owner and tracking who it is.
That answer is called ownership, and we start on it next time!
Activity 20
Let's talk glitches!
- I'll play a video from YouTube - you make note of what kinds of bugs you see
- You'll answer two questions on Gradescope about the video
- If we have time we'll watch a second one
Lecture 21 - Ownership: the three rules, moves, and copies
Announcements
Remember this murky situation in Python?
What happens to a when we change b?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
What does this print, and why?
[1, 2, 3, 4]. b = a didn't copy the list, it copied the address of the list. So we have two variables pointing to the same value.
So how does Python know when you're done with that part of memory?
It counts references. It adds one when you make a new reference and subtracts one when references go away, and frees the memory when the count hits zero.
That count is checked while your program runs, which costs time!
Rust's solution: Ownership
Ownership tracks what variable is responsible for data that is on the heap.
- It helps efficiently free up memory when it is no longer needed (better than Python)
- It helps prevent "undefined behavior" that arises from less-strict approaches (better than C)
Learning Objectives
By the end of today, you should be able to:
- State the three ownership rules
- Say which types are
Copy, and why everything else moves - Predict whether a program compiles after a move, including a move into or out of a function
- Draw a move and a clone on a stack and heap diagram
Rust's Three Ownership Rules
These are the fundamental rules that make Rust memory-safe:
- Each value in Rust has an owner
- There can only be one owner at a time
- When the owner goes out of scope, the value will be dropped
Rule 1: Each value in Rust has an owner
#![allow(unused)] fn main() { let s1 = String::from("hello"); // s1 owns the string // There is exactly ONE owner of the "hello" data on the heap }
Stack: Heap:
┌─────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ s1: String │ │ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
│ ├ ptr ──────┼─▶│ │ │ │ │ │
│ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 5 │
└─────────────┘
Rule 2: There can only be one owner at a time
fn main() { let s1 = String::from("hello"); let s2 = s1; // Ownership MOVES from s1 to s2 // println!("{}", s1); // ERROR! s1 no longer owns the data println!("{}", s2); // OK! s2 now owns it }
What happens in memory:
Before move: After move:
Stack: Stack:
┌─────────────┐ ┌─────────────┐
│ s1: String │ │ s2: String │
│ ├ ptr ──────┼──┐ │ ├ ptr ──────┼─┐
│ ├ len: 5 │ │ │ ├ len: 5 │ │
│ └ cap: 5 │ │ │ └ cap: 5 │ │
└─────────────┘ │ ├─────────────┘ │
│ │ s1: (moved) │ │
│ └─────────────┘ │
│ │
│ Heap: │
│ ┌─────┬─────┬─────┬─────┬─────┐
└─▶│ 'h' │ 'e' │ 'l' │ 'l' │ 'o' │
└─────┴─────┴─────┴─────┴─────┘
This looks the same as Python but it's different
b = a # Python: two names, one list, both usable
let s2 = s1; // Rust: two names, one string, only s2 usable
The heap looks identical in both languages. One allocation, and a second variable now pointing at it.
Python allows both names and keeps a count. Rust has the second name take over and the first one is killed.
Both approaches are valid, but there are trade-offs.
Rule 3: When the owner goes out of scope, the value is dropped
fn main() { { let s = String::from("hello"); // s owns the string } // s goes out of scope, heap memory is freed automatically! println!("{}", s); // error: there is no s here anymore }
Rule 3 is what makes it all work.
Before, we had to remember to call libc::free by hand. Rule 3 is the compiler doing that call for you every time a variable goes out of scope, and since there's only one owner, it never happens twice!
Move vs Copy
An i32 gets copied
#![allow(unused)] fn main() { let x = 5; let y = x; // x is copied to y println!("{} {}", x, y); // Both work! }
A String gets moved
#![allow(unused)] fn main() { let s1 = String::from("hello"); let s2 = s1; // s1 is moved to s2 // println!("{}", s1); // s1 is no longer valid println!("{}", s2); // Only s2 works now }
Why would an int get copied but a string get moved by default?
Think-pair-share
Because copying the i32 is cheap: it is 4 bytes on the stack.
Copying the String would mean either copying just the 24-byte handle (creating two pointers, with those dangers), or making a duplicate of all the characters too, which takes up lots of room. So by default it's a move.
If you want the characters fully copied, you can say .clone() (we'll see it in a minute).
The short list of types that copy
A type copies when copying its bytes gives you two complete values with nothing shared. These are called Copy types:
- Integers and floats:
i32,u8,usize,f64, ... boolandchar- Tuples and arrays made only of these
&Ttypes (like&str). A second read-only pointer is cheap and low-risk
Everything else moves.
"Stack types copy, heap types move" is almost always true, with a couple of small exceptions. Your own structs and enums, for example, move unless you tell them to copy.
If you want a real ("deep") copy, ask for it with .clone()
fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); // new heap block, letters copied println!("{} {}", s1, s2); // both work }
Stack: Heap:
┌──────────────────────┐
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────┼────▶│ h │ e │ l │ l │ o │
│ │ len: 5 │ └───┴───┴───┴───┴───┘
│ │ cap: 5 │
│ └ s2: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────┼────▶│ h │ e │ l │ l │ o │
│ len: 5 │ └───┴───┴───┴───┴───┘
│ cap: 5 │
└──────────────────────┘
Two handles, two blocks of letters, two owners.
.clone() always compiles, which makes it tempting. But it also duplicates every byte on the heap. When the compiler complains about a move, clone is one fix, but not always the best one. (We'll see more options shortly!)
Your own structs move
struct Point {
x: i32,
y: i32,
}
struct NamedPoint {
name: String,
point: Point,
}
fn main() {
let p1 = Point { x: 3, y: 4 };
let home = NamedPoint { name: String::from("home"), point: p1 };
let work = NamedPoint { name: String::from("work"), point: p1 };
println!("{} {}", home.name, work.name);
}
Compiles, compiler error, or runtime panic?
A compiler error. p1 moved into home, so there is nothing left to put in work.
A struct copies only if you tell it to, and only if all its fields are Copy types. You can do that the same way you told it about Debug and PartialEq:
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
Copy requires Clone as a prerequisite, so the two usually appear together.
Passing data to functions follows the same move/copy rules
fn takes_ownership(some_string: String) { println!("in fn: {}", some_string); } // some_string goes out of scope and heap memory is freed fn makes_copy(some_integer: i32) { println!("in fn: {}", some_integer); } // some_integer goes out of scope, but it's just a copy fn main() { let s = String::from("hello"); takes_ownership(s); // s is moved into the function // println!("in main: {}", s); // ERROR! s is no longer valid let x = 5; makes_copy(x); // x is copied into the function println!("in main: {}", x); // OK! x is still valid }
Function return values also transfer ownership
fn gives_ownership() -> String { let some_string = String::from("yours"); some_string // Ownership moves to caller } fn takes_and_gives_back(a_string: String) -> String { a_string // Ownership moves back to caller } fn main() { let s1 = gives_ownership(); // Ownership moves from function to s1 let s2 = String::from("hello"); // s2 comes into scope let s3 = takes_and_gives_back(s2); // s2 moves in, s3 gets it back // s2 is no longer valid, but s1 and s3 are println!("s1: {}", s1); // println!("s2: {}", s2); println!("s3: {}", s3); }
Let's draw these moves on the board!
Step 1: inside gives_ownership, just before it returns.
Stack: Heap:
┌──────────────────────────┐
│ gives_ownership() │
│ └ some_string: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
├──────────────────────────┤
│ main() │
│ ├ s1: String = ??? │
│ ├ s2: String = ??? │
│ └ s3: String = ??? │
└──────────────────────────┘
Step 2: after it returns.
Stack: Heap:
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░ gives_ownership() (gone) ░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░
┌──────────────────────────┐
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ │ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
│ ├ s2: String = ??? │
│ └ s3: String = ??? │
└──────────────────────────┘
Step 3: inside takes_and_gives_back.
Stack: Heap:
┌──────────────────────────┐
│ takes_and_gives_back() │
│ └ a_string: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────────┼───▶│ h │ e │ l │ l │ o │
│ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
├──────────────────────────┤
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ │ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
│ ├ s2: (moved out) │
│ └ s3: String = ??? │
└──────────────────────────┘
Step 4: at the end of main.
Stack: Heap:
┌──────────────────────────┐
│ main() │
│ ├ s1: String │ ┌───┬───┬───┬───┬───┐
│ │ ptr ─────────────────┼───▶│ y │ o │ u │ r │ s │
│ │ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
│ ├ s2: (moved out) │
│ └ s3: String │ ┌───┬───┬───┬───┬───┐
│ ptr ─────────────────┼───▶│ h │ e │ l │ l │ o │
│ len: 5, cap: 5 │ └───┴───┴───┴───┴───┘
└──────────────────────────┘
Try to predict what happens before running:
Think-pair-share
fn main() { let s1 = String::from("world"); let s2 = process_string(s1); println!("{}", s2); // Will this work? println!("{}", s1); // Will this work? } fn process_string(input: String) -> String { let greeting = format!("Hello, {}!", input); greeting }
Monday's bugs vs today's rules
| Bug from Monday | What Rust does | Rule |
|---|---|---|
| Leak: nobody frees it | The owner frees it at its closing brace | 3 |
| Double-free: two pointers, each frees it | let s2 = s1 moves. Only s2 is freed | 1 and 2 |
| Use-after-free: freed, then used | A moved or dropped value cannot be used | 2 and 3 |
Use-after-free, written in Rust:
fn main() {
let data = String::from("hello");
drop(data); // free it now, by hand
println!("{}", data); // bug 2
}
error[E0382]: borrow of moved value: `data`
3 | drop(data);
| ---- value moved here
4 | println!("{}", data);
| ^^^^ value borrowed here after move
drop is just a function that takes ownership and does nothing with it. Rule 3 does the rest at its closing brace.
Take-aways
- Three rules: every value has one owner, only one at a time, and it is dropped at the owner's closing brace
Copytypes copy: numbers,bool,char, and&T. Everything that owns heap data moves- A move hands over the handle. The heap does not change.
.clone()makes a second heap block.- Passing to/from a function follows the same rules
- Rule 3 is
free, done for you, exactly once
Activity 21
See activities/activity_21.md. Acting out ownership.
Two quick questions on Gradescope, after Act 1 and after Act 3.
Lecture 22 - Owning collections: Vec, String, and capacity
Announcements
The three rules - do you remember them?
- Each value in Rust has an owner
- There can only be one owner at a time
- When the owner goes out of scope, the value will be dropped
Learning Objectives
By the end of today, you should be able to:
- Say what
pushdoes to a vector'slenandcap - List the four steps
pushtakes when the vector is full, and say why doubling keeps that rare - Explain why
names[0]can't move aStringout of aVec<String> - Make a
Box<T>and say when you might use it
We've been using Vec for weeks
We've been coding them, drawing them, and you're writing your own in Project 2 right now.
Today we get to two questions we've been able to dodge until now:
- What does a
Vecown, and what happens to that when you index into it? - What happens when it runs out of room?
Review: creating a Vec
fn main() { let numbers: Vec<i32> = Vec::new(); // empty, type from the annotation let scores = vec![85, 92, 78]; // with initial data let names: Vec<String> = Vec::new(); // empty, will hold Strings println!("{:?} {:?} {:?}", numbers, scores, names); }
scores in memory: 24-byte handle on the stack, the elements on the heap:
Stack: Heap:
┌─────────────────┐ ┌────┬────┬────┐
│ scores: Vec<i32>│ │ 85 │ 92 │ 78 │
│ ├ ptr ──────────┼─────▶│ │ │ │
│ ├ len: 3 │ └────┴────┴────┘
│ └ cap: 3 │
└─────────────────┘
Review: the basic operations
fn main() { let mut numbers = vec![1, 2, 3]; // Add elements (might reallocate!) numbers.push(4); numbers.push(5); println!("Vec: {:?}", numbers); // Other basic operations numbers.pop(); let num_len = numbers.len(); // Access elements (copies the value!) let first = numbers[0]; let third = numbers[2]; println!("First: {}, Third: {}, len {}", first, third, num_len); println!("Vec: {:?}", numbers); }
Capacity vs length
fn main() { let mut vec = Vec::with_capacity(4); // reserve room for 4, hold 0 println!("len {}, cap {}", vec.len(), vec.capacity()); vec.push(1); vec.push(2); println!("len {}, cap {}", vec.len(), vec.capacity()); vec.push(3); vec.push(4); println!("len {}, cap {}", vec.len(), vec.capacity()); vec.push(5); // no room. Now what? println!("len {}, cap {}", vec.len(), vec.capacity()); }
You've written this. Vec::with_capacity is your FastVec::with_capacity. The jump from 4 to 8 is Growth::Double.next_capacity(4), and the fifth push is your push.
What push does when the vector is full
Four steps (that all show up in Project 2):
- Ask the allocator for a bigger block:
next_capacity(4)= 8 - Copy every element from the old block into the new one
- Write the new element into the first free slot
- Free the old block
Before push(5):
Stack Heap
┌───────────┐ ┌───┬───┬───┬───┐
│ vec │ │ 1 │ 2 │ 3 │ 4 │
│ ├ ptr ────┼───▶│ │ │ │ │
│ ├ len: 4 │ └───┴───┴───┴───┘
│ └ cap: 4 │ full
└───────────┘
After push(5):
Stack Heap
┌───────────┐ ┌───┬───┬───┬───┐
│ vec │ │ x │ x │ x │ x │ freed
│ ├ ptr ──┐ │ └───┴───┴───┴───┘
│ ├ len: 5│ │ ┌───┬───┬───┬───┬───┬───┬───┬───┐
│ └ cap: 8│ │ │ 1 │ 2 │ 3 │ 4 │ 5 │ ? │ ? │ ? │
└─────────┼─┘ │ │ │ │ │ │ │ │ │
└─────▶└───┴───┴───┴───┴───┴───┴───┴───┘
The handle on the stack never moved. Its ptr and cap changed, and len went up by one, same as any push.
Why double, not add one? Doubling means most pushes find room and cost nothing; the copy happens rarely. Adding one would copy on every push. You'll explore the impact in Project 2!
Indexing copies the value out
fn main() { let numbers = vec![10, 20, 30, 40]; // These copy values from heap to stack: let first = numbers[0]; // first = 10 (copied) let second = numbers[1]; // second = 20 (copied) // Original Vec still owns the heap data: println!("Vec still works: {:?}", numbers); println!("Copied values: {}, {}", first, second); }
Stack: Heap:
┌─────────────────┐
│ main() │
│ ├ numbers: Vec │ ┌────┬────┬────┬────┐
│ │ ├ ptr ───────┼─────▶│ 10 │ 20 │ 30 │ 40 │
│ │ ├ len: 4 │ └────┴────┴────┴────┘
│ │ └ cap: 4 │
│ ├ first: 10 │
│ └ second: 20 │
└─────────────────┘
i32 is Copy, so numbers[0] copies the value from heap to stack. The vector still owns everything on the heap. Nothing moved.
Drawing practice: a Vec<String>
let names = vec![
String::from("Alice"),
String::from("Bob"),
];
Draw names in memory. Stack on the left, heap on the right, all types and metadata.
What about Vec<String>?
Heap data inside heap data. Each element is itself a handle, pointing at its own block of letters.
fn main() { let names = vec![ String::from("Alice"), String::from("Bob"), ]; // let first_name = names[0]; // does not compile. Why not? println!("{:?}", names); }
Think-pair-share: numbers[0] copied a 10 out. What would names[0] have to do?
Stack: Heap: More Heap:
┌───────────────────┐ ┌─────────────────┐ ┌─────┬─────┬─────┬─────┬─────┐
│ names: Vec<String>│ │ String "Alice" │ │ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ ├ ptr ────────────┼────▶│ ├ ptr ──────────┼───────▶┤ │ │ │ │ │
│ ├ len: 2 │ │ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ └ cap: 2 │ │ └ cap: 5 │
└───────────────────┘ ├─────────────────┤ ┌─────┬─────┬─────┐
│ String "Bob" │ │ 'B' │ 'o' │ 'b' │
│ ├ ptr ──────────┼───────▶┤ │ │ │
│ ├ len: 3 │ └─────┴─────┴─────┘
│ └ cap: 3 │
└─────────────────┘
String isn't Copy.
- Copying the handle would make two owners of the same letters, which breaks rule 2.
- Moving it out would leave a hole in the vector.
So anything that takes names[0] as a value, like let first = names[0]; or passing it to a function, is an error.
Looking at it in place is fine: names[0].len(), println!("{}", names[0]), and names[0].clone() all compile.
Box: a Vec of length one
You know what a Vec does. It puts values on the heap and keeps a small handle on the stack that points at them.
A Box<T> is the same idea for exactly one value. The handle is just the pointer: no len, no cap, because there's always one thing at the other end.
fn main() { let x = 42; // an i32 on the stack, as usual let b: Box<i32> = Box::new(42); // the same i32, on the heap, with a pointer to it println!("{} {}", x, b); } // b goes out of scope: the heap block is freed. Automatically.
Stack: Heap:
┌────────────────┐
│ main() │
│ ├ x: 42 │ ┌────┐
│ └ b: Box<i32> │ │ 42 │
│ └ ptr ──────┼──────▶│ │
└────────────────┘ └────┘
So a box puts anything on the heap, even a type that would normally sit on the stack, and gives you one pointer that owns it.
The box owns what it points at. Rule 3 does the rest: when the box is dropped, the value at the other end is freed with it. Same as a Vec, same as a String.
Why bother, for a 42? You wouldn't. We use Box when values are too big for the stack, or when the value has a size we can't know, like in trees later in the semester.
The same three rules apply for Box
fn main() { let b: Box<i32> = Box::new(42); println!("{}", b); drop(b); // destroys the box, which frees the 42 on the heap println!("{}", b); // the compiler knows b is gone }
Wednesday this was a String, and Monday it was C's use-after-free. C compiled it. Rust refuses, for a box the same as for anything else.
Box for data too big for the stack
Sometimes data that would usually go on the stack is just too big:
fn main() { let small_data = [0; 1000]; // 4 KB on the stack: fine let huge_data = [0; 10_000_000]; // 40 MB. The stack is 8 MB println!("{} and {} numbers", small_data.len(), huge_data.len()); }
Run it. The program never reaches the println!: the frame for main is too big to build.
The fix is to build it on the heap in the first place, and keep one small owner on the stack:
fn main() { let huge_data: Box<[i32]> = vec![0; 10_000_000].into_boxed_slice(); println!("Successfully created {} numbers", huge_data.len()); }
Box<[i32]> is a box owning ten million numbers. On the stack it's one pointer and one length.
When do you need a box?
- Large data: millions of records, big matrices
- Deep structures: nested data where the size isn't known up front
- Recursive types: lists and trees, which is Lecture 34
Boxes in boxes
You can put anything in a box, including things that already own heap data:
fn main() { // Box containing a Vec of Strings (heap in heap in heap!) let boxed_names = Box::new(vec![ String::from("Alice"), String::from("Bob"), ]); println!("Names in box: {:?}", boxed_names); // Box in a Box (why not?) let box_in_box = Box::new(Box::new(42)); println!("Deeply boxed value: {}", box_in_box); }
boxed_names: stack has aBoxpointer, heap has theVechandle, heap has theStringhandles, heap has the lettersbox_in_box: stack has aBoxpointer, heap has anotherBoxpointer, heap has the42
Activity 22, Part 1: the Box Office
Everything you need is now on the table: a Vec<String>, a push that runs out of room, a Box<Vec<String>>, and a box in a box.
See Activity 22. Cast to the front. Everyone else gets the sheet and the first question: which variables in main are still usable on the last two lines?
The same job, three prices
| Who decides when to free | When | What it costs you | |
|---|---|---|---|
| C | You | You write free | Seven kinds of bug |
| Python | Reference count, plus a collector for cycles | While the program runs | Time on every assignment, and pauses |
| Rust | The compiler, from the ownership rules | Before the program runs | Arguing with the borrow checker |
Rust moved the cost from run time to your time, which is a good trade-off if the program runs more often than you write it (like most programs!).
Take-aways
- A
Vec<T>is a stack handle (ptr, len, cap) pointing at heap elements. Same shape asString - Capacity isn't length. Growing past capacity allocates, copies, and frees, which shows up in Project 2's
push. Doubling keeps that rare. - Indexing a
Vec<i32>copies out a value. Indexing aVec<String>can't, because that would make two owners - A
Box<T>is like a Vec-of-one, or a pointer that owns what it points at - Boxes and vectors follow the same three rules as everything else
Activity 22, Part 2: three programs that won't compile
See Activity 22. Read the compiler message, say what went wrong in terms of owners, and write two fixes.
Lecture 23 - Strings: why they're so complicated
Announcements
Friday's loose end
Earlier, we saw names[0] couldn't take a String out of a vector.
Today we see a similar problem:
fn main() { let text = String::from("hello"); let c = text[0]; println!("{}", c); }
You can't take a character out of a String either!
A Vec<char> would let you. A String won't. Why?
And one more:
fn main() { println!("{}", "🦀".len()); }
What will this print?
By the end of today both of these will make (some) sense.
Learning Objectives
By the end of today, you should be able to:
- Tell
String,&str, and&Stringapart, and draw each one - Say what a slice is and why it has no capacity
- Explain why
text[0]doesn't compile, and what.len()counts - Use
.chars(),.iter(), and.collect()to take text apart and put it back
A slice is a view
A slice is a reference to a contiguous run of elements inside something else.
Think of it as a window through which you can see some of the elements.
fn main() { let data = [1, 2, 3, 4, 5, 6]; let slice1 = &data[1..4]; // [2, 3, 4] let slice2 = &data[..3]; // [1, 2, 3], from the start let slice3 = &data[2..]; // [3, 4, 5, 6], to the end println!("{:?} {:?} {:?}", slice1, slice2, slice3); }
The type is &[T]: a slice of Ts, a view onto someone else's array (or array-like thing). start..end includes start and stops before end, the same as a for range.
You've sliced before
Syntax like Python, behavior like numpy.
arr = np.array([1, 2, 3, 4, 5, 6])
view = arr[1:4] # a VIEW into arr's buffer, no copy
view[0] = 99 # arr is now [1, 99, 3, 4, 5, 6]
df.iloc[1:4] # pandas: same syntax, view or copy?
A numpy slice is a window onto the original array, which is exactly what &data[1..4] is.
Pandas is the cautionary tale: whether .iloc[1:4] gave you a view or a copy depends on the version and the dtypes! (You've probably seen those SettingWithCopyWarnings lots of times.)
Rust is clear and consistent: &[T] is always a view.
A slice in memory
let v = vec![10, 20, 30, 40, 50];
let x = &v[1..4]; // the 20, 30, 40
Stack: Heap:
┌─────────────────┐
│ main() │ ┌────┬────┬────┬────┬────┐
│ ├ v: Vec<i32> │ │ 10 │ 20 │ 30 │ 40 │ 50 │
│ │ ├ ptr ───────┼──────────▶│ │ │ │ │ │
│ │ ├ len: 5 │ └────┴────┴────┴────┴────┘
│ │ └ cap: 5 │ ▲
│ └ x: &[i32] │ │
│ ├ ptr ───────┼──────────────────┘ (at the 20)
│ └ len: 3 │
└─────────────────┘
A slice has two parts: a pointer and a length. It points into the heap, not at the handle. There's no cap, because the slice can't grow.
That makes it a "fat pointer" that points to a range in memory.
Activity 23, Problem 1: draw the slice
See Problem 1 on Activity 23.
Three and two. data is pointer, length, capacity. slice is pointer and length only. No capacity, because a slice doesn't own what's on the heap and can't grow it.
Slices of anything contiguous
fn main() { let a = [1, 2, 3, 4, 5]; let a_slice: &[i32] = &a[1..4]; println!("{:?}", a_slice); let v = vec![1.1, 2.2, 3.3, 4.4, 5.5]; let v_slice: &[f64] = &v[2..]; println!("{:?}", v_slice); let s = String::from("Hello World"); let s_slice: &str = &s[0..5]; println!("{}", s_slice); let smaller: &[f64] = &v_slice[0..2]; // a slice of a slice println!("{:?}", smaller); }
&[T]is a slice of an array or aVec&stris a slice of text. Same two things, pointer and length.
Mutable slices
fn main() { let mut numbers = [10, 20, 30, 40, 50]; { let slice = &mut numbers[1..4]; slice[0] = 999; // index 0 of the slice is index 1 of the array } // the slice ends here println!("{:?}", numbers); // [10, 999, 30, 40, 50] }
Indexes are relative to the slice, not to the array underneath.
Heads down: two slices, no overlap
What happens?
let mut data = vec![1, 2, 3, 4];
let slice1 = &data[0..2];
let slice2 = &mut data[2..4];
println!("{:?} {:?}", slice1, slice2);
A) Compiles fine. The slices don't overlap: indexes 0 and 1 versus 2 and 3
B) Compiler error: Rust stops you from doing something risky
C) Runtime panic
B. The two slices really don't overlap, and the compiler rejects it anyway.
There's a rule about mixing & and &mut that explains this, and we'll get to it soon.
The handle, or the text?
Two ways to point at a String:
fn main() { let s = String::from("Hello"); let whole: &String = &s; let text: &str = &s[..]; // all of s's text, as a &str println!("address of s {:p}", &s); println!("s's ptr {:p}", s.as_ptr()); println!("whole points to {:p}", whole); println!("text points to {:p}", text); }
whole matches the address of s. It points at the handle, on the stack.
text matches s's ptr. It points at the letters, on the heap, and carries a length.
Three types of string
let s = String::from("Hello"); // owned: a handle on the stack, letters on the heap
let s_ref: &String = &s; // a reference to the handle
let slice: &str = &s[..]; // a slice of the letters: pointer + length
let literal: &str = "literal"; // also a slice, but of text baked into the program
Stack: Heap:
┌───────────────────┐
│ main() │ ┌─────┬─────┬─────┬─────┬─────┐
│ ├ s: String │◀──┐ │ 'H' │ 'e' │ 'l' │ 'l' │ 'o' │
│ │ ├ ptr ─────────┼───┼───▶│ │ │ │ │ │
│ │ ├ len: 5 │ │ └─────┴─────┴─────┴─────┴─────┘
│ │ └ cap: 5 │ │ ▲
│ ├ s_ref: &String ─┼───┘ │
│ ├ slice: &str │ │
│ │ ├ ptr ─────────┼───────────┘
│ │ └ len: 5 │ Program binary (read-only):
│ └ literal: &str │ ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ ├ ptr ─────────┼───────▶│ 'l' │ 'i' │ 't' │ 'e' │ 'r' │ 'a' │ 'l' │
│ └ len: 7 │ └─────┴─────┴─────┴─────┴─────┴─────┴─────┘
└───────────────────┘
Stringowns its letters. Three fields:ptr,len,cap&Stringis one arrow, to the handle&stris a slice:ptrandlen, nocap. The letters can be on the heap, or in the program itself. A literal like"literal"is compiled into the binary and lives for the whole run
&str parameters take both
fn analyze_text(text: &str) -> usize { text.len() } fn main() { let s = String::from("Hello"); let s_ref: &String = &s; println!("{}", analyze_text(s_ref)); // &String, converted for you println!("{}", analyze_text(&s)); // same thing println!("{}", analyze_text("literal")); // &str directly }
When you hand a &String to a function that wants a &str, Rust converts it for you.
So we generally use &str in signatures. A function taking &str accepts a &String, a literal, or a piece of either. A function taking &String accepts only &String.
&str in, String out is the usual shape for a function that builds new text.
Activity 23, Problem 2: two frames
See Problem 2 on Activity 23.
Three ways to join text
fn main() { // 1. format!: works with anything, and you keep all of it let name = "Data"; let num = 210; let result = format!("{} Science {}", name, num); // 2. push_str: add onto the end of a String you already have let mut s = String::from("Hello"); s.push_str(" World"); // 3. +: the left side must be a String, and it gets used up let s1 = String::from("Hello"); let s2 = s1 + " World"; // s1 is gone after this line println!("{} | {} | {}", result, s, s2); }
format! is a safe default.
Why the crab is 4 bytes long
Unicode gives every character in every writing system a number, its code point:
| Character | Code point |
|---|---|
A | U+0041 |
é | U+00E9 |
你 | U+4F60 |
🦀 | U+1F980 |
A Rust char holds that number directly, so a char is always 4 bytes.
UTF-8 is the way those numbers are written into memory and files. It's variable-length: the first 128 code points take one byte each, so plain ASCII text is unchanged, and everything else takes two, three, or four.
Character UTF-8 bytes Bits
'A' 1 01000001
'é' 2 11000011 10101001
'你' 3 11100100 10111101 10100000
'🦀' 4 11110000 10011111 10100110 10000000
A Rust String is UTF-8. Its len counts those bytes.
len is bytes, chars is characters
fn main() { let emoji = "🦀🚀"; println!("bytes {}, chars {}", emoji.len(), emoji.chars().count()); let accents = "Aé"; println!("bytes {}, chars {}", accents.len(), accents.chars().count()); }
.len() counts bytes, .chars().count() counts characters. When a string test is off by one or two, this is usually why.
So that's why text[0] is rejected
If text[0] compiled, it would have to return one byte. For "🦀" that is the first quarter of a crab, which isn't a character at all. Rust refuses at compile time rather than hand you garbage.
The safe way to look at the pieces is .chars(), which is Part 3. First, a question.
Heads down: what happens?
fn main() { let emoji = "🦀"; let slice = &emoji[0..2]; println!("{}", slice); }
A) Prints 🦀
B) Prints nothing
C) Compiler error
D) Runtime panic
D. Slicing is by bytes and the boundary check happens at run time. Byte 2 is inside the crab, so the program panics.
Slicing by byte range compiles
text[0] is refused at compile time. &text[0..2] isn't: the range is checked at run time, and the check is "does each end land on a character boundary?"
fn main() { let text = "Hello, world!"; println!("{}", &text[0..5]); // "Hello": every ASCII character is one byte let text = "🦀Hello"; println!("{}", &text[4..9]); // "Hello": starts right after the 4-byte crab println!("{}", &text[0..4]); // "🦀": the whole crab is fine }
On plain ASCII, byte positions and character positions agree, so this works and tests pass. The first accented name or emoji in the data is where they break down.
chars, iter, and collect
You can't get far with text without these. .chars() and .iter() let you break variable-sized characters up, and .collect() is how you put them back together.
.iter() and .collect() are much more powerful than just this, but we'll wait til the end of the term to explore them more. For now, they do stuff like this:
fn main() { // iterate characters, not bytes for ch in "Hi!".chars() { println!("{}", ch); // ch is a char } // char to String let c: char = '🦀'; let s: String = c.to_string(); // iter() over a Vec gives you sum, max, and friends let numbers = vec![1, 2, 3, 4, 5]; let total: i32 = numbers.iter().sum(); let largest = numbers.iter().max(); // Some(5); None if empty println!("s: {} total: {} largest: {:?}", s, total, largest); }
collect builds whatever type you ask for
The type annotation on the left is the instruction.
fn main() { let letters = vec!['H', 'e', 'l', 'l', 'o']; let word: String = letters.iter().collect(); // chars into a String println!("{}", word); let text = "Hello"; let chars: Vec<char> = text.chars().collect(); // a String into chars println!("{:?}", chars); let first_three: String = "Hello World".chars().take(3).collect(); // and back println!("{}", first_three); }
Vec<char> is the one type where [0] works on text, because every element is exactly one char. It costs 4 bytes a character.
Heads down: which would you write?
Two ways to keep the first three characters:
// A: takes &mut, changes the caller's String in place
fn keep_first_three(s: &mut String) {
*s = s.chars().take(3).collect();
}
// B: takes &str, returns a new String
fn first_three(s: &str) -> String {
s.chars().take(3).collect()
}
A) A
B) B
C) Depends on context
C, with B as the default. A changes the caller's text and needs &mut. B leaves the original alone and creates a new String. A is only right if the caller wants to completely replace the original.
Lecture 24 - Borrowing: the two rules
Announcements
The one-character fix
We saw this bug before:
fn main() { let names = vec![String::from("Alice"), String::from("Bob")]; let first = names[0]; println!("{}", first); }
What might be a one-character fix?
&names[0] because it does not take the String out of the vector. It only asks to look at it.
The one-owner rule is not broken, because no second owner was created.
This is using references for borrowing, and it is our focus for today and Friday.
Learning Objectives
By the end of today, you should be able to:
- Explain what a borrow is, and why
&names[0]compiles whennames[0]doesn't - Draw a reference into a
Vec, and say whatpushcan do to it - State the two borrowing rules, and say what bugs each one prevents
- Predict whether a program compiles by tracking each borrow from where it's made to its last use
- Read a borrow-checker error and say which line keeps the borrow alive
- Draw a struct that owns a
String, and anOptionorResult, on the stack and heap
Our three kinds of pointers
A pointer is an address. We've now met all three kinds Rust has:
- Raw pointers: an address and nothing else. Unchecked, so they often need
unsafe - Owning pointers:
Box,Vec,String. The address plus the job of freeing what's at the other end - References:
&Tand&mut T. The address, but no ownership, and the compiler has restrictions for when these are okay
Borrowing is the verb: making a reference is borrowing, and the owner is lending. L ike borrowing a book: your friend still owns it, you read it while you have it, you give it back, and they can use it afterward.
Today we go over the rules for when the compiler lets you borrow or not.
Why Rust has strict rules on borrowing
Here is the bug the rules exist to prevent. Remember what push does when the vector is full:
let mut data = vec![1, 2, 3, 4, 5]; // cap 5, full
let slice = &data[1..3]; // points into the heap, at the 2
data.push(6); // no room: allocate bigger, copy, free the old
println!("{:?}", slice); // slice still points at the old block
Before push: After push:
Stack: Heap: Stack: Heap:
┌────────────────┐ ┌───┬───┬───┬───┬───┐ ┌────────────────┐ ┌╌╌╌┬╌╌╌┬╌╌╌┬╌╌╌┬╌╌╌┐
│ data ──────────┼──▶│ 1 │ 2 │ 3 │ 4 │ 5 │ │ data ──────────┼─┐ ╎ 1 ╎ 2 ╎ 3 ╎ 4 ╎ 5 ╎ freed
│ slice ─────────┼──────▶│ │ │ │ slice ─────────┼─┼────▶╎ ╎ ╎
└────────────────┘ └───┴───┴───┴───┴───┘ └────────────────┘ │ └╌╌╌┴╌╌╌┴╌╌╌┴╌╌╌┴╌╌╌┘
│ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
└▶│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
slice is now the C lecture's bug 2, use-after-free, and the program would print whatever landed in the old block.
A reader was looking at the data, a writer moved it, and the reader never found out. That is what the rules have to prevent.
The two borrowing rules
- Rule 1. At any moment, you can have either any number of
&references or exactly one&mutreference. Never both - Rule 2. A reference must never outlive what it points at
Rule 1 is the trickier one! There's a lot of nuance, and we'll go over it.
Rule 2 leads to the idea of "lifetimes", which we start today and finish on Friday.
Each rule is one of the C bugs, turned into a compiler error:
| Rule | Bug it prevents | How |
|---|---|---|
| 1 | Use-after-free through reallocation; data races | Nobody can change the data while someone else is looking at it |
| 2 | Dangling pointers | A reference cannot survive without its data |
Remember Rule 1 as "many readers or one writer".
Rule 1 in three programs
Many readers:
fn main() { let greeting = String::from("hello"); let r1 = &greeting; let r2 = &greeting; let r3 = &greeting[..2]; println!("{} {} {}", r1, r2, r3); // all read-only, all fine }
One writer:
fn main() { let mut greeting = String::from("hello"); let w = &mut greeting; w.push_str(" world"); println!("{}", w); // the only reference, fine }
A reader and a writer:
fn main() { let mut greeting = String::from("hello"); let r = &greeting; // reader let w = &mut greeting; // writer, while the reader is still in use println!("{} {}", r, w); // error }
The tricky part: the original name counts too!
Changing a value through its own name is a mutable borrow.
fn main() { let mut x = 10; let y = &x; // reader x = 20; // error: this is a write, while y is still reading println!("{}", y); }
error[E0506]: cannot assign to `x` because it is borrowed
The original variable does not get special privileges. While another reference is alive, nobody is allowed to change the data through any path.
Reorder it and it compiles:
fn main() { let mut x = 10; let y = &x; println!("{}", y); // last use of y: the borrow ends here x = 20; // fine, nobody is reading println!("{}", x); }
A borrow ends at its last use
At the last line that uses it. The closing brace is usually later.
fn main() { let mut n = 10; let r = &n; // reader starts println!("Reading: {}", r); // reader's last use: borrow over let m = &mut n; // writer starts *m += 5; println!("After: {}", m); // writer's last use: borrow over let r2 = &n; // a new reader println!("Again: {}", r2); }
Readers and writers, one after another, never at the same time. Three borrows of n, zero conflicts, because none of them overlap.
Activity 24, Problem 1: be the borrow checker
See Problem 1 on Activity 24.
Compiles. reader is made on line 4 and last used on line 5, so its borrow is over before writer is made on line 7. A reader, then a writer, never both at once.
Reading the error
The compiler tells you which rule, and marks all three places. Which borrow is the reader, which is the writer, and which line keeps the reader alive?
fn main() { let mut text = String::from("Hello"); let read = &text; println!("{}", read); let write = &mut text; write.push_str(" World"); println!("{} {}", read, write); }
error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
|
3 | let read = &text;
| ----- immutable borrow occurs here
5 | let write = &mut text;
| ^^^^^^^^^ mutable borrow occurs here
7 | println!("{} {}", read, write);
| ---- immutable borrow later used here
read is the reader, made on line 3. write is the writer, made on line 5. Line 7 keeps the reader alive: it prints read after the writer exists, so the two borrows overlap.
Without line 7, read's last use would be line 4, its borrow would be over before write was made, and the program would compile.
The fix isn't to delete the &mut. It's to finish reading before you start writing.
On the midterm you will get a program like this, an abridged error, and the question "which rule, and how would you fix it." The three markers are the answer.
Rule 2: a reference cannot outlive its data
We talked about the "dangling pointer" issue in the bug lecture.
Here we see how a borrowing rule prevents it in Rust.
fn get_name() -> &str { let name = String::from("Alice"); // name owns "Alice" on the heap &name[..] // hand back a pointer into it... } // ...and name is dropped. The heap block is freed fn main() { let n = get_name(); // n points at the freed block println!("Hello, {}", n); // use-after-free, if this ever ran }
Rust refuses to compile it: there is no value for it to be borrowed from. How does it know?
What a lifetime is
Lifetime: how long a piece of data is valid.
{
let x = 5; // ────┐ x's lifetime starts
let r = &x; // │ r borrows x
println!("{}", r); // │
} // ────┘ x's lifetime ends, and r must be done by here
The compiler tracks the lifetime of every value, and checks that no reference is used past the end of the lifetime of what it points at. get_name fails because name ends at the closing brace, and the returned reference would be used after it.
Most of the time Rust works all of this out by itself. Friday: the cases where it asks you to spell it out.
Activity 24, Problem 2: rule 2 on paper
See Problem 2 on Activity 24.
Does not compile, rule 2. inner lives from line 4 to the closing brace on line 7. outer's borrow runs from line 5 to line 8, past the end of inner. The error says so in three places: inner declared here, dropped here while still borrowed, and borrow later used here.
Let's review: References into a collection
Earlier we saw that numbers[0] copies the value out, because i32 is Copy.
&numbers[0] is different: it points into the heap, at the element itself.
For a Vec<String>, you have to use references (or cloning) - you can't do let name = names[0].
fn main() { let names = vec![String::from("Alice"), String::from("Bob")]; // let name = names[0]; // ERROR: cannot move out of index let name_ref = &names[0]; // borrow the element let name_clone = names[0].clone(); // or copy it, at a cost println!("Referenced name: {}", name_ref); println!("Cloned name: {}", name_clone); }
Stack: Heap:
┌──────────────────────┐ Vec buffer
│ main() │ ┌─────────────────┐
│ ├ names: Vec<String> │ ┌───▶│ String "Alice" │ ┌─────┬─────┬─────┬─────┬─────┐
│ │ ├ ptr ────────────┼──────┼───▶│ ├ ptr ──────────┼────▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │ ├ len: 2 │ │ │ ├ len: 5 │ └─────┴─────┴─────┴─────┴─────┘
│ │ └ cap: 2 │ │ │ └ cap: 5 │
│ ├ name_ref: &String ─┼──────┘ ├─────────────────┤
│ │ (to [0]) │ │ String "Bob" │ ┌─────┬─────┬─────┐
│ └ name_clone: │ │ ├ ptr ──────────┼────▶│ 'B' │ 'o' │ 'b' │
│ String │ │ ├ len: 3 │ └─────┴─────┴─────┘
│ ├ ptr ───────────┼───┐ │ └ cap: 3 │
│ ├ len: 5 │ │ └─────────────────┘
│ └ cap: 5 │ │ ┌─────┬─────┬─────┬─────┬─────┐
└──────────────────────┘ └──────▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │ (the clone)
└─────┴─────┴─────┴─────┴─────┘
vec[i] tries to copy or move the value out. For a type that is not Copy, write &vec[i] to borrow it.
A struct that owns a String
struct Player { name: String, score: u32, } fn main() { let p = Player { name: String::from("Alice"), score: 10 }; let whole = &p.name; // at the handle, inside p let start = &p.name[..3]; // into the heap, at the text println!("{} {} {}", whole, start, p.score); }
Stack: Heap:
┌─────────────────────────────┐
│ main() │
│ ├ p: Player │
│ │ ├ name: String │◀──┐ ┌─────┬─────┬─────┬─────┬─────┐
│ │ │ ├ ptr ────────────────┼───┼──────▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │ │ ├ len: 5 │ │ └─────┴─────┴─────┴─────┴─────┘
│ │ │ └ cap: 5 │ │ ▲
│ │ └ score: u32 = 10 │ │ │
│ ├ whole: &String ───────────┼───┘ │
│ └ start: &str │ │
│ ├ ptr ──────────────────┼─────────────┘
│ └ len: 3 │
└─────────────────────────────┘
A struct's fields sit inline in the frame, so p is a handle and a number, side by side. whole points at the handle, start points past it into the text.
Both are borrows of p.name, and the rules apply to a field exactly as they do to a variable.
Option and Result in memory
While structs have fixed fields, enums have variants.
An enum has as its value it's particular variant, and any data included in that variant.
fn main() { let a: Option<i32> = None; let b: Option<i32> = Some(3); let c: Result<i32, String> = Err(String::from("bad input")); let names = vec![String::from("Al"), String::from("Bo")]; let d: Option<&String> = names.first(); println!("{:?} {:?} {:?} {:?}", a, b, c, d); }
Stack: Heap:
┌────────────────────────────┐
│ main() │
│ ├ a: Option<i32> = None │
│ ├ b: Option<i32> = Some(3) │
│ ├ c: Result<i32, String> │
│ │ = Err(String) │ ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ │ ├ ptr ──────────────┼─────────▶│ 'b' │ 'a' │ 'd' │ ' ' │ 'i' │ 'n' │ 'p' │ 'u' │ 't' │
│ │ ├ len: 9 │ └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
│ │ └ cap: 9 │
│ ├ names: Vec<String> │ Vec buffer
│ │ ├ ptr ────────────────┼─────────▶┌──────────────┐
│ │ ├ len: 2 │ │ String "Al" │ ┌─────┬─────┐
│ │ └ cap: 2 │ ┌───▶│ ├ ptr ───────┼────▶│ 'A' │ 'l' │
│ └ d: Option<&String> │ │ │ ├ len: 2 │ └─────┴─────┘
│ = Some(&String) ──────┼─────┘ │ └ cap: 2 │
└────────────────────────────┘ ├──────────────┤
│ String "Bo" │ ┌─────┬─────┐
│ ├ ptr ───────┼────▶│ 'B' │ 'o' │
│ ├ len: 2 │ └─────┴─────┘
│ └ cap: 2 │
└──────────────┘
On a diagram, write the variant and its value where the variable is, just like basic copy types If the value has a pointer, draw the pointer and the data on the heap.
Take-aways
- A borrow is a reference with no ownership. Making one is borrowing, and the owner is lending
- Rule 1: any number of
&, or exactly one&mut, never both at once. The owner's own name counts as a writer - Rule 2: a reference never outlives what it points at
- A borrow ends at its last use, which is usually before the closing brace
- A
&mutinto part of a vector is a&mutto the whole vector, becausepushcan move everything - The error marks three places: where the reader was made, where the writer was made, and the later use that keeps the reader alive
- On a diagram, a struct's fields sit inline, and an enum is its variant and value where the variable is
Friday: what the rules mean for the functions you write, and when you have to spell out a lifetime.
Activity 24
See Activity 24. Be the borrow checker: nine programs, bracket every borrow, and decide what the compiler says. Problems 1 and 2 are done, so start at Problem 3.
Lecture 25 - Borrowing in practice: functions, iteration, and lifetimes
Announcements
Learning Objectives
By the end of today, you should be able to:
- Choose between
&T,&mut T, andTfor a function parameter - Use
*to read or write through a reference - Change every element of a vector in place with
iter_mut()and* - Bracket a value's lifetime against a borrow of it, and say whether a call site compiles
- Read
'ain a function signature and say what it promises
Three things a function can ask for
Every function signature makes a choice about the data you hand it. There are three.
1. "Let me look at it." fn midpoint(v: &Vec<i32>)
The function gets an address it can read from but not write or move.
2. "Let me change it." fn add_zero(v: &mut Vec<i32>)
Also an address, but with "edit access".
3. "Give it to me." fn consume(v: Vec<i32>)
The function gets the data itself, and the caller's variable is finished: it moved.
When a function asks for option 3, the caller still has a choice: hand over the original, or hand over v.clone() and keep the original.
Why would you ever hand over ownership?
consume didn't need to. It read one number, and a reference would have done. Functions ask for T when they're going to put the value somewhere that outlives the call.
Into a collection:
#![allow(unused)] fn main() { fn enroll(roster: &mut Vec<String>, name: String) { roster.push(name); } }
Try name: &String and push refuses: "expected String, found &String". The vector holds Strings.
Into a struct:
#![allow(unused)] fn main() { struct Player { name: String, score: u32 } fn new_player(name: String) -> Player { Player { name, score: 0 } } }
Same shape. The Player goes back to the caller and lives on, so the name has to live inside it.
A reference is a loan, and a loan can't go in a box that outlives it. That's why constructors take String, and why .to_string() keeps showing up right before a struct literal.
What each argument costs
Our first fix for ownership errors was to .clone(), and that often works. So why not clone whenever the compiler complains?
Let's see the same one-line body, one million elements, once by reference and once by clone.
fn midpoint_ref(v: &Vec<i32>) -> usize { v.len() / 2 } fn midpoint_own(v: Vec<i32>) -> usize { v.len() / 2 } use std::time::Instant; fn main() { let mut my_vec = Vec::with_capacity(1_000_000); for i in 0..1_000_000 { my_vec.push(i); } let time = Instant::now(); let mid = midpoint_ref(&my_vec); // pass a reference println!("by reference: {:?}", time.elapsed()); let time = Instant::now(); let mid2 = midpoint_own(my_vec.clone()); // hand over a copy println!("by clone: {:?}", time.elapsed()); println!("{} {}", mid, mid2); }
#![allow(unused)] fn main() { fn midpoint_ref(v: &Vec<i32>) -> usize { v.len() / 2 } fn midpoint_own(v: Vec<i32>) -> usize { v.len() / 2 } }
main builds a vector of a million numbers, then times midpoint_ref(&my_vec) against midpoint_own(my_vec.clone()).
Why is the second one so much slower?
clone() copies all elements to a new space on the heap, and then throws them away.
Passing a reference copies 8 bytes. Cloning copies 4 megabytes.
All the trade-offs
| How | Speed | Function can modify? | Caller keeps it? |
|---|---|---|---|
&T, shared reference | Fast | No | Yes |
&mut T, mutable reference | Fast | Yes | Yes |
T, given away | Fast | Yes | No |
T, but cloned first | Slow | Yes | Yes |
So which should you use?
Rules of thumb:
- Start with
&T. Most functions only need to look - If the function has to change the caller's data,
&mut T - If the function stores the data somewhere that outlives the call, take it:
T - Reach for
.clone()only when you need two copies that will diverge: one gets changed, the other stays put. Know what it costs
Try it. For each, which signature?
- A function that prints a vector
- A function that removes all the even numbers from a vector
- A function that returns a sorted copy, leaving the original alone
&Vec<i32>. It only reads&mut Vec<i32>. It changes the caller's vector in place&Vec<i32>in, a newVec<i32>out. The clone happens inside, once, because the job is defined as making a copy. Cloning at the call site would make two
Using &mut T as a parameter
&mut means the function can change the caller's data, and the caller sees it afterward.
fn main() { let mut message = String::from("Hello"); modify_string(&mut message); println!("{}", message); // "Hello!!!" } fn modify_string(text: &mut String) { text.push_str("!!!"); }
Three things to notice:
messagemust bemutto begin with- The caller writes
&mut message - Inside,
text.push_strauto-dereferences. For plain assignment,*text = ...
Let's watch it in memory. (You can draw along on your sheets)
Step 4: after the call
Stack: Heap:
┌───────────────────────┐
│ main() │
│ └ message: String │ ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ ├ ptr ─────────────┼────────────────▶│ 'H' │ 'e' │ 'l' │ 'l' │ 'o' │ '!' │ '!' │ '!' │
│ ├ len: 8 │ └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
│ └ cap: 10 │
└───────────────────────┘
modify_string's frame is gone, and the borrow ended with it. message is the only name left, and it owns the new, longer text.
Steps 1 to 4. Draw it once, then update it as we go.
Activity 25, Problem 1: draw what crosses the frame
See Problem 1 on Activity 25.
Two frames. main holds a (15 after the marked line) and b (5). process holds x and y, both arrows pointing back into main's frame. Nothing is on the heap. The data never moved; process only ever had the addresses.
Review of *: follow the arrow
Remember how raw pointers needed * to read, references did not (auto-dereferencing)?
Here's a recap of when that works and when we still need *
fn main() { let x = 42; let y = 10; let x_ref = &x; let y_ref = &y; let sum = *x_ref + *y_ref; // follow both arrows, add the values println!("Sum: {}", sum); let sum2 = x_ref + y_ref; // also fine: + is defined for references too println!("Sum: {}", sum2); println!("x_ref: {}", x_ref); // println! follows the arrow for you println!("*x_ref: {}", *x_ref); // same thing, written out println!("{}", *x_ref > 5); // comparisons need the * // println!("{}", x_ref > 5); // uncomment: expected `&_`, found integer }
When do you need it?
- Comparisons on the value:
*x_ref > 5,*x_ref == 10. - Assigning through a
&mut:*r = 5
When it's optional (auto-dereferencing)
- Math:
x_ref + 1and*x_ref + 1are both fine - Displaying/printing like
println!andformat! - Method calls like
.len(), or.push()or even.clone()
You are always safe writing the * yourself. If it wasn't needed, nothing breaks.
Two muts in one line
*r = value changes the data behind a mutable reference. But you might also want to change where the reference itself points. That takes its own mut.
fn main() { let mut x = 5; let mut y = &mut x; *y = 10; // change the value y points at println!("y is now: {}", y); println!("x is now: {}", x); // 10 let mut z = 6; y = &mut z; // point y at something else println!("y is now: {}", y); }
The two assignments do different things:
*y = valuechanges whatypoints aty = &mut otherchanges whereypoints
In practice: read, then write
Most real code separates its reading phase from its writing phase, and then the rules never bite.
fn main() { let mut scores = vec![85, 92, 78, 96, 88]; let (total, average) = analyze(&scores); // reader, borrow ends at return println!("Total: {}, Average: {:.1}", total, average); normalize(&mut scores); // writer, borrow ends at return println!("Normalized: {:?}", scores); } fn analyze(data: &Vec<i32>) -> (i32, f64) { let sum: i32 = data.iter().sum(); (sum, sum as f64 / data.len() as f64) } fn normalize(data: &mut Vec<i32>) { let max = *data.iter().max().unwrap(); for item in data.iter_mut() { *item = *item * 100 / max; } }
A function's borrow ends when the function returns, unless it hands a reference back. So two calls in a row never conflict.
normalize has one new thing in it: iter_mut().
.iter() lends, .iter_mut() lends mutably
fn main() { let mut numbers = vec![1, 2, 3, 4, 5]; for num in numbers.iter() { // num: &i32, a reader println!("{}", num); // *num += 1; // error: cannot assign through a & reference } for num in numbers.iter_mut() { // num: &mut i32, a writer *num += 10; // follow the arrow and change what is there } println!("{:?}", numbers); // [11, 12, 13, 14, 15] let mut names = vec![String::from("Alice"), String::from("Bob")]; for name in names.iter_mut() { // name: &mut String name.push_str("!"); // a method, so no * needed } println!("{:?}", names); // ["Alice!", "Bob!"] }
Each loop borrows the whole vector for the length of the loop.
Reading & and * in a loop
for num in v.iter() gives you references, not values. There are two (and a half) ways to get the value out:
fn main() { let numbers = vec![10, 20, 30]; for num_ref in numbers.iter() { // num_ref: &i32 let squared = *num_ref * *num_ref; // deref by hand // let squared = num_ref * num_ref // or auto-deref println!("{}", squared); } for &num in numbers.iter() { // num: i32, copied out by the pattern let squared = num * num; println!("{}", squared); } let names = vec![String::from("Alice"), String::from("Bob")]; for name in names.iter() { // name: &String println!("{}", name.len()); // methods auto-deref } // for &name in names.iter() { } // error: cannot move out of a reference }
The & in a pattern says "match a reference, bind what it points to." That copies the value out, so it only works for Copy types. For a String, keep the reference and use it; or .clone() if you need your own.
Four ways to loop over a vector
| Loop | Each item is | The vector afterward |
|---|---|---|
for x in v.iter() | &T | untouched |
for x in &v | &T, same thing | untouched |
for x in v.iter_mut() | &mut T | changed in place |
for x in v | T | moved, or copied for a Copy type |
.enumerate() works on any of them and adds the index: for (i, x) in v.iter_mut().enumerate() gives (usize, &mut T).
Lifetimes: when they can be inferred
Borrow checker rule 2: a reference must never outlive what it points at.
Sometimes the compiler can check lifetimes itself and error if the rule would be violated:
fn main() { let outer; // declared here, set later { let inner = vec![1, 2, 3]; outer = &inner; println!("Inside: {:?}", outer); } println!("Outside: {:?}", outer); }
Lifetimes: when they CAN'T be inferred
longest hands back one of its two inputs. Whose lifetime does the result have to stay inside?
fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } fn main() { let a = String::from("long string"); let b = String::from("short"); println!("{}", longest(&a, &b)); }
The returned reference points at one of the inputs, and the compiler cannot tell which. So it cannot check rule 2 for the caller.
Reading explicit lifetimes
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } fn main() { let a = String::from("long string"); let b = String::from("short"); println!("{}", longest(&a, &b)); }
'a is pronounced "tick a". Read the signature as: "the result lives no longer than the shorter-lived of x and y."
<'a>declares a name for a lifetime, the way<T>would declare a type&'a stron an input says "this is one of the references the result might point at"&'a stron the output says "the result borrows from one of those"
It changes nothing about how long anything lives. It is a promise the compiler then checks: if the caller lets a or b die while the result is still in use, that is a rule 2 error.
Let's draw out the borrow checker's work here
Bracket a, b, and result. Does it compile?
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } fn main() { let a = String::from("long string"); let result; { let b = String::from("short"); result = longest(&a, &b); } println!("{}", result); }
'static, and what you actually have to do
One special lifetime is 'static which means "lives for the whole program."
let s: &'static str = "Hello world"; // a literal, stored in the program binary
fn greeting() -> &'static str { "Hello!" } // nothing to borrow from: it is always there
String literals are 'static, which is why we draw them in the program binary and not on the heap.
In practice, you will rarely write a lifetime. When you do need one, the compiler says so and suggests the annotation. Your job would be to read it:
<'a>means the function returns a borrow of one of its inputs'staticmeans the data is there for the whole program- If a snippet on an exam has an
'aor'staticin it, that is what it means. But I'm not going to ask you to reason about it directly.
Activity 25
See Activity 25. Diagrams and trade-offs. Problem 1 is done, so start at Problem 2.
Lecture 26 - Tests: writing them, and what to test
Announcements
You have been running tests like this on your projects
Every cargo test --test cp1 ran this, among others:
#[test]
fn push_then_get_numbers() {
let mut v = SlowVec::new();
v.push(1);
v.push(33);
v.push(-5);
assert_eq!(v.get(0), &1);
assert_eq!(v.get(2), &-5);
assert_eq!(v.get(1), &33);
}
What would have happened if you ran cargo test when your get implementation had an off-by-one error in it?
The test's name in red, and then two values: what the get() returned on the left, what the test expected on the right.
Today we'll understand how to write tests like this ourselves.
Learning Objectives
By the end of today, you should be able to:
- Write a unit test with
#[test]and theassertmacros, and run it withcargo test - Predict whether a given test passes or fails, and why
- Name a case that a function's tests miss
- Write a test from a signature and a one-line description
Why write tests?
Everyone's code has bugs. Not writing tests is like not wearing a seatbelt because you think you will never get in an accident.
What we all do at first:
- Write code
- Run it, see if it works
- Fix bugs
- Hope you didn't break something else
With tests:
- Write code
- Write tests
- Run them every time you change anything
- The tests catch when you broke something else
Even better:
- Write tests that determine the behavior you want
- Write code until they pass
That is called test-driven development, and it is how all our projects are set up!
The simplest test
A test is a function with #[test] on it.
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
Run with cargo test:
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed
A real test
// Our code
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
// Our test
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
assert_eq!(add(-1, 1), 0);
assert_eq!(add(0, 0), 0);
}
Three parts:
#[test], which tellscargo testto run it- A name, which is what you will see when it fails
- Assertions: things that must be true
The three asserts
assert!(condition) checks that something is true:
#[test]
fn test_positive() {
let x = 5;
assert!(x > 0);
}
assert_eq!(left, right) checks that two things are equal, and prints both when they are not:
#[test]
fn test_length() {
let v = vec![1, 2, 3];
assert_eq!(v.len(), 3);
}
assert_ne!(left, right) checks that two things differ:
#[test]
fn test_different() {
assert_ne!(String::from("hello"), String::from("world"));
}
All three panic when they fail. Panicking is how a test fails.
Including an error message in assert
Any assert takes a message after the condition. You see it only when the test fails, which is exactly when you want it.
#[test]
fn test_score_in_range() {
let score = calculate_score(&data);
assert!(
score >= 0.0 && score <= 100.0,
"Score should be between 0 and 100, but got: {}",
score
);
}
The same works for assert_eq! and assert_ne!: the two values come first, then the message, then anything the message's {} slots need, in order, the same shape as println!.
#[test]
fn test_round_total() {
let total = round_total(&rolls, player);
assert_eq!(
total,
18,
"wrong total for player {} in round {}",
player,
round
);
}
Where tests live
Convention: a tests module at the bottom of the file they test.
pub fn is_even(n: i32) -> bool {
n % 2 == 0
}
#[cfg(test)]
mod tests {
use super::*; // bring in everything from the file above
#[test]
fn test_is_even() {
assert!(is_even(2));
assert!(is_even(0));
assert!(!is_even(3));
}
}
#[cfg(test)]means "only compile this forcargo test". Your real binary does not carry its testsuse super::*is why the test can callis_evenwithout a path
Project 2 did it the other way, with a tests/ directory next to src/. Both work.
Running tests
$ cargo test
running 3 tests
test tests::test_is_even ... ok
test tests::test_average_single ... ok
test tests::test_average_empty ... FAILED
failures:
---- tests::test_average_empty stdout ----
note: test did not panic as expected
test result: FAILED. 2 passed; 1 failed
Three things to read, in order: the name of what failed, the note under it, and the count.
cargo test # everything
cargo test --test cp1 # one file in tests/
cargo test average # every test with "average" in its name
Good tests test one thing at a time
One test, three functions:
#[test]
fn test_everything() {
assert_eq!(add(1, 2), 3);
assert_eq!(multiply(2, 3), 6);
assert_eq!(divide(10, 2), 5);
}
Three tests:
#[test]
fn test_add() { assert_eq!(add(1, 2), 3); }
#[test]
fn test_multiply() { assert_eq!(multiply(2, 3), 6); }
#[test]
fn test_divide() { assert_eq!(divide(10, 2), 5); }
Why? When test_everything fails, you know one of three things broke. When test_divide fails, you know which.
Good tests: expect the panic
Sometimes a function should panic:
pub fn get_first(v: &Vec<i32>) -> i32 {
v[0] // panics on an empty vector
}
#[test]
#[should_panic]
fn test_empty_vec() {
get_first(&vec![]); // the test passes only if this panics
}
Even better, say which panic you expect:
#[test]
#[should_panic(expected = "index out of bounds")]
fn test_empty_vec() {
get_first(&vec![]);
}
Without expected, a test that panics for the wrong reason still passes.
Good tests: the edges
The "happy path" is how things work normally, and is worth testing.
More important, in some ways, is testing edge cases that are off the happy path.
pub fn average(numbers: &[i32]) -> i32 {
let sum: i32 = numbers.iter().sum();
sum / numbers.len() as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_average_normal() {
assert_eq!(average(&[1, 2, 3]), 2);
}
#[test]
fn test_average_single() {
assert_eq!(average(&[42]), 42);
}
#[test]
#[should_panic]
fn test_average_empty() {
average(&[]); // integer division by zero panics
}
}
Empty. One element. Zero. Negative. The biggest value that fits. Ask what could go wrong, then write that down as a test.
Will this test pass?
Same average as before. Which of these tests pass? Think/pair/share.
pub fn average(numbers: &[i32]) -> i32 {
let sum: i32 = numbers.iter().sum();
sum / numbers.len() as i32
}
#[test]
fn a() { assert_eq!(average(&[2, 4]), 3); }
#[test]
fn b() { assert_eq!(average(&[1, 2, 5]), 3); }
#[test]
#[should_panic]
fn c() { average(&[]); }
apasses. 6 / 2 is exactly 3bfails. 8 / 3 is 2.67, so 3 looks like the right answer. Integer division throws the remainder away and returns 2. The test reportsleft: 2, right: 3, and now you have to decide which one is wrong: the function, for truncating, or the test, for expecting a rounded answercpasses. Integer division by zero panics, and#[should_panic]is satisfied
Reading a test is reading the code and the expectation, and either one can be wrong.
What does this test miss?
From Project 2. Your next_capacity had visible tests like these (abridged):
#[test]
fn double_doubles() {
assert_eq!(Growth::Double.next_capacity(4), 8);
}
#[test]
fn add_adds() {
assert_eq!(Growth::Add(3).next_capacity(4), 7);
}
#[test]
fn multiply_rounds_down() {
assert_eq!(Growth::Multiply(1.5).next_capacity(5), 7);
}
They all pass for this implementation, yet there are still bugs here. What input breaks it, and what test could check for it?
pub fn next_capacity(&self, capacity: usize) -> usize {
match self {
Growth::Double => capacity * 2,
Growth::Add(n) => capacity + n,
Growth::Multiply(f) => (capacity as f64 * f) as usize,
}
}
The input: Capacity 0.
Double returns 0, and push has nowhere to go. Also Multiply(1.0), or Multiply(1.1) on a small capacity, where rounding down lands on the same number.
The spec said "the answer must always be bigger than capacity" but no (visible) test checked.
The secret test that does check it:
// The handout promises only that the answer is bigger than `capacity`, so
// that is all this checks. These are the cases where the arithmetic alone
// does not get there; any bigger number is a pass.
#[test]
fn always_grows_even_when_the_arithmetic_does_not() {
let cases: Vec<(Growth, usize)> = vec![
(Growth::Double, 0),
(Growth::Multiply(1.5), 0),
(Growth::Multiply(1.5), 1),
(Growth::Multiply(1.1), 5),
(Growth::Multiply(1.0), 4),
(Growth::Multiply(0.5), 4),
(Growth::Add(0), 4),
(Growth::Add(0), 0),
];
for (growth, capacity) in cases {
let next = growth.next_capacity(capacity);
assert!(next > capacity, "{:?}.next_capacity({}) returned {}, which is not bigger",
growth, capacity, next);
}
}
Activity 26, Problem 1: plan the tests
See Problem 1 on Activity 26.
Beyond unit tests
Unit tests check one function in isolation.
Integration tests check that the parts work together, and in Rust they live in a tests/ directory next to src/, which is what Project 2's cp1.rs, cp2.rs, and cp3.rs were.
my_project/
src/
lib.rs # unit tests at the bottom of each file
tests/
cp1.rs # integration tests: use the crate like a user would
The car gap story
A few more habits for good test design
- Test behavior, not implementation If you rewrite the inside of a function, its tests should still pass
- Do not test the language
assert_eq!(vec![1, 2].len(), 2)can never fail, so it can never tell you anything. - Keep tests independent Each one runs on its own, in any order
- Lean into wordy test names
panic_if_first_value_in_vec_is_zerois a lot more informative thancheck_zeroor worse,test_7
Take-aways
- A test is a function with
#[test], and it fails by panicking. Theassertmacros are how you panic on purpose - Run them with
cargo test. Read the name, then the note, then the count - One thing per test. Edges over happy paths: empty, one, zero, too big
- A test can be wrong too
- A failing test names the bug, which is why the name is worth writing well
Wednesday: review. Friday: Midterm 2.
Activity 26
See Activity 26. Problem 1 is done, so start at Problem 2: the playground, your six tests, and the bug they find.
Lecture 27 - Review: everything before Midterm 2
Announcements
Welcome to Review Day, again
Three weeks of memory, one hour on Friday. Today we'll:
- Go back over the ideas, in five groups
- Try a few quick questions on each
- Sort what you need to know from what was context
- Spend the last twenty minutes on a confidence quiz and each other's questions
Reminders about the exam
- Friday, this room, this time, 50 minutes
- No notes, no devices
- The practice test has the same five sections and the same point values, and solutions are up today
And for after:
- Corrections. Discussion in about 2 weeks, like last time, up to half lost points back
- A strong final counts for more.
What's on it
Everything from the stack lecture through Monday's tests lecture: the stack and the heap, pointers and unsafe, ownership, Vec and Box, strings and slices, the two borrowing rules, and tests.
The code on the paper uses structs, enums, match, and loops, so those still have to be ready, but every question is about this unit.
The sections
| Section | Points | |
|---|---|---|
| 1 | Quick recall | 20 |
| 2 | Why does this not compile | 18 |
| 3 | Safety | 12 |
| 4 | Stack and heap | 32 |
| 5 | Hand-coding | 18 |
Same shape as the practice test. Look through the whole thing before you start and make a plan.
1. Memory and pointers (Lectures 17 to 19)
Key concepts
- Memory is a numbered strip of bytes. An address is a number. A pointer is a variable holding an address
- The stack: one frame per function call, thrown away whole when the function returns. Fast because every size is known ahead of time. A
{ }inside a function is a mini-frame; aletinside it is a new variable that dies at the end - Stack overflow: a function that never stops calling itself fills the stack
- The heap is for sizes decided while the program runs. A
StringorVecis a handle on the stack,ptr,len,cap, with the data on the heap. A&stror&[T]is a pointer and a length, into data that belongs to someone else - The CPU reads memory in chunks and keeps them in a cache, so walking along a row of a
Vec<Vec<i32>>is faster than walking down a column *means two things. In a type, "pointer to". In an expression, follow it. A reference is a pointer with rules; a raw pointer has none, so following one needsunsafe- Three places an arrow can end: the stack (
&x), the heap (&v[1]), or the program binary (a literal). The type alone doesn't tell you which
What's not important: real addresses, how the allocator picks a block, or how big the cache is.
Quick questions: memory and pointers
Question 1
Which of these puts data on the heap?
- A)
let a = 5; - B)
let b = [1, 2, 3]; - C)
let c = String::from("hi"); - D)
let d = "hi";
Answer. C.
Question 2
A String handle carries three numbers. A &str carries two. Which two, and which one is missing?
Answer. A &str has a pointer and a length. It has no capacity, because it doesn't own the letters and can't grow them.
Question 3
#![allow(unused)] fn main() { let v = vec![10, 20, 30]; let r = &v[1]; }
Where does r's arrow end on a diagram?
- A) At
v's handle, on the stack - B) At the
20, on the heap - C) At the
10, on the heap - D) In the program binary
Follow-up: and if it werelet r = &v;?
Answer. B. &v[1] is a reference to one element, so the arrow goes straight to the 20 in the heap block. &v would point at the handle instead.
Question 4
Draw the stack and the heap at // DRAW HERE, with a type on every variable.
fn main() { let x = 7; let v = vec![10, 20, 30]; let label: &str = "scores"; let r_x = &x; let r_20 = &v[1]; // DRAW HERE println!("{} {} {}", r_x, r_20, label); }
Answer.
Stack: Heap: Program binary (read-only):
┌──────────────────────────┐
│ main() │
│ ├ x: i32 = 7 │◀─┐
│ ├ v: Vec<i32> │ │ ┌────┬────┬────┐
│ │ ├ ptr ────────────────┼──┼──────▶│ 10 │ 20 │ 30 │
│ │ ├ len: 3 │ │ └────┴────┴────┘
│ │ └ cap: 3 │ │ ▲
│ ├ label: &str │ │ │ ┌──────────┐
│ │ ├ ptr ────────────────┼──┼──────────────┼────────▶│ "scores" │
│ │ └ len: 6 │ │ │ └──────────┘
│ ├ r_x: &i32 ─────────────┼──┘ │
│ └ r_20: &i32 ────────────┼─────────────────┘
└──────────────────────────┘
2. Bugs, unsafe, and ownership (Lectures 20 to 22)
Key concepts
- The seven bugs: leak, use-after-free, double free, dangling pointer, buffer overflow, null pointer, data race. Be able to go back and forth between the name and a short description
unsafemeans taking responsibility. The compiler can't check a raw pointer, so you promise it's valid.mallocgives bytes with garbage in them; you write before you read, and youfreeexactly once- Three ownership rules: every value has an owner, only one at a time, and it is dropped when the owner goes out of scope. Rule 3 is
freedone for you, always once - Move or copy. Numbers,
bool,char, and&Tcopy. Anything that owns heap data moves: the handle changes hands and the heap doesn't change. Your own struct moves unless you#[derive(Clone, Copy)] .clone()makes a second heap block.- Passing to a function follows the same rules. Returning hands ownership back out
Vecgrowth: whenlenreachescapand youpush, it asks for a bigger block, copies the elements, writes the new one, and frees the old blockBox::new(x)putsxon the heap with a pointer on the stack that owns it
What's not important: reading C, writing unsafe yourself
Quick questions: bugs and ownership
Question 5
For each mistake, what does safe Rust do about it: compile error, panic when it runs, or prevented automatically (there is no way to write it)?
- a) Use a
Stringafter moving it into a function - b) Forget to free a
Vec
Answer. a) Compile error. The compiler knows the value moved. b) Prevented automatically. The owner drops it at the end.
Question 6
Does this compile? If not, which line, and which rule?
#![allow(unused)] fn main() { let s1 = String::from("hello"); let s2 = s1; let s3 = s1.clone(); println!("{}", s2); }
Answer. No. Line 3: s1 moved into s2 on line 2, so there is nothing left to clone. Rule 2, one owner at a time.
Question 7
v1 is a Vec<i32> holding three numbers. After let v2 = v1;, how many copies of the three numbers are on the heap? And after let v2 = v1.clone(); instead?
- A) 0 and 1
- B) 1 and 1
- C) 1 and 2
- D) 2 and 2
Answer. C.
3. Strings and slices (Lecture 23)
Key concepts
- Three types of string.
Stringowns letters on the heap.&Stringpoints at the handle.&strpoints at letters, on the heap or in the binary. Write&strin signatures: it accepts a&String, a literal, or a slice .len()is bytes..chars().count()is characters. Plain ASCII letters are 1 byte each, accented letters likeéorñare 2, Chinese, Japanese, and Korean characters are 3, and emoji are 4. Slicing is by byte, so&s[0..2]can land inside a character and panic, ands[0]doesn't compile at all- A slice is a view: a pointer and a length into data that belongs to someone else, so it has no capacity.
&s[1..3]on aStringand&v[1..3]on aVecor an array are the same idea .chars()walks the characters,.collect()builds aStringback out of them
What's not important: the actual bit patterns of UTF-8, or anything about format! beyond {} and {:?}.
Quick questions: strings and slices
Question 8
Explain in one sentence why this panics.
#![allow(unused)] fn main() { let text = "🦀Hello"; let slice = &text[0..2]; }
Answer. The crab is four bytes, so byte 2 is in the middle of it, and Rust refuses to hand out half a character. The message says byte index 2 is not a char boundary.
Question 9
What does this print?
#![allow(unused)] fn main() { let v = vec![10, 20, 30, 40, 50]; let a = &v[1..4]; let b = &a[1..]; println!("{} {} {:?}", a[0], b[0], b); }
Answer. 20 30 [30, 40]. A slice counts from its own start, so a[0] is the 20 at v's index 1, and a is [20, 30, 40]. b is a slice of that slice, from a's index 1 on, so it is [30, 40] and b[0] is the 30. All three point into the same five numbers on the heap: a.ptr at the 20 with len 3, b.ptr at the 30 with len 2.
4. Borrowing (Lectures 24 and 25)
Key concepts
- Rule 1: any number of
&, or exactly one&mut, never both at once. The owner's own name counts as a writer - Rule 2: a reference never outlives what it points at
- A borrow lasts until its last use, which is usually before the closing brace. The error marks three places: the reader, the writer, and the later use that kept the reader alive
- A
&mutinto part of a vector is a&mutto the whole vector, becausepushcan move everything - Three things a function can ask for.
&Tto look.&mut Tto change the caller's data.Tto keep it..clone()at the call site when you need two copies that will diverge, and know what it costs - In
let mut r = &mut y;the firstmutletsrbe re-pointed, the second letsychange through it with*r - Lifetimes, read only.
<'a>on a function means it returns a borrow of one of its inputs.'staticmeans the data is there for the whole program, which is why literals live in the binary
What's not important: deciding whether a lifetime annotation is needed, writing one, or exactly when auto-deref happens.
Quick questions: borrowing
Question 10
Fill in the two blanks so this compiles and prints [90, 95, 83].
fn update_scores(scores: _____, bonus: i32) { for score in scores.iter_mut() { *score += bonus; } } fn main() { let mut data = vec![85, 90, 78]; update_scores(_____, 5); println!("{:?}", data); }
Answer. &mut Vec<i32> and &mut data.
Question 11
Where is the borrow checker error here, and why?
#![allow(unused)] fn main() { let mut x = vec![1, 2, 3]; let r1 = &x; x.push(4); println!("{:?}", r1); }
Answer. The push on line 3 is a writer, and r1 is a reader that is still alive because it is used on line 4. Rule 1, one writer or many readers.
5. Tests (Lecture 26)
Key concepts
- A test is a function with
#[test]above it, no parameters, no return. It fails by panicking, andassert!,assert_eq!,assert_ne!, and#[should_panic]are how you panic on purpose - Any assert takes a message after its values. You only see it when the test fails, which is exactly when you want it
- One thing per test. The happy path is worth a test. The edges are worth more: empty, one, zero, exactly on the boundary
- A test can be wrong too. Reading a test means reading the code and the expectation
- Write one from a signature and a sentence. The description usually hands you the ordinary case and one edge for free
What's not important: setting up a tests module from memory, or cargo test flags.
Quick question: tests
Question 12
A classmate's test:
fn empty_input() {
assert_eq!(count_long(&[], 4), 0);
}
Two things are missing before this does its job. What are they?
Answer. The #[test] line above it, without which cargo test never runs it, and a message after the values, so a failure says what was expected in words: "no words means nothing is long". The test itself is a good edge case.
Tips by exam section
Recall. One line or one word per blank. If one stumps you, write your best guess and move on.
Why does this not compile. Read the compiler's message for what it expected and what it found. The fix is often a line above the one it points at, and sometimes two lines, a signature and its call. For the borrowing ones, bracket each borrow from where it is made to its last use before you decide which rule.
Safety. Read the unsafe program in order, and think about what has to be going on in memory for it to work. For an edit, it can help to draw out for yourself what's happening in memory to figure out what the bug is.
Stack and heap. Don't forget types! Write every variable with its type before drawing an arrow, including the ones the function hasn't used yet. ptr, len, cap on a handle; ptr and len on a slice. Frames bottom-up, a dashed box for a { }, ??? for no value yet. Arrows need to be precise.
Hand-coding. Signature first, then the skeleton, then the details. The other code snippets on the exam can be references for good syntax, so use them.
Activity 27: Confidence check + passing sheets
See Activity 27.
Like last time - it's not a quiz. Read each line, mark Got it, Shaky, or Study it, and keep the sheet for studying.
Submit photos on gradescope when you're done.
At the same time
I'll pass out a few sheets, some marked "Q&A" and some marked "Tips and Encouragement"
- The Q&A sheet is divided up with sections where you can write a question for others to answer, about content or studying or anything else. When you get the sheet, you can answer in the same box
- The tips and encouragement sheet is open to writing anything anywhere
I'll scan them all and post them after
Lecture 29 - Traits: shared behavior across types
Announcements
Learning objectives
By the end of today, you should be able to:
- Define a trait and implement it for your own types
- Use a default method, and know when to override it
- Explain what
#[derive(Debug)]has been doing all this time - Implement
Ordso your own type can be sorted - Hold values of different types in one
VecwithBox<dyn Trait>
One button, many effects
Many headphones have a physical pause/play button for convenience - but how does it work?
- You're listening to music on Spotify... the button pauses the music
- You're listening to a podcast on a podcast app... the button pauses that
- You're watching a YouTube video... the pause button stops both video and audio
How do the headphones know how to pause all three?
The headphones don't know, they just send the message: "Pause!"
Each app wrote its own way to respond to that command.
We call that agreement to implement a command (or commands) a "trait".
The problem: the same job, written twice
A Player and a Team. We want to print a card for each:
struct Player { name: String, number: u32, team: String }
struct Team { name: String, wins: u32, losses: u32 }
fn describe_player(p: &Player) -> String {
format!("#{} {}, {}", p.number, p.name, p.team)
}
fn describe_team(t: &Team) -> String {
format!("{} ({}-{})", t.name, t.wins, t.losses)
}
Two functions with similar jobs.
Add a Coach, a Stadium, a Season, and now we have five functions to remember.
A trait is the promise
trait Describe {
fn describe(&self) -> String;
}
This says: any type that implements Describe has a describe method that borrows the value and returns a String.
There's no body. The trait says what the method looks like. Each type says how.
From other languages: this is an interface in Java, a protocol in Swift, an abstract base class in Python.
How each type keeps its promise
impl Describe for Player {
fn describe(&self) -> String {
format!("#{} {}, {}", self.number, self.name, self.team)
}
}
impl Describe for Team {
fn describe(&self) -> String {
format!("{} ({}-{})", self.name, self.wins, self.losses)
}
}
impl Describe for Player: "here is how a Player describes itself."
Same shape as the impl Player { } blocks we've been writing since the structs lecture, with the trait's name added.
Same bodies as before. The difference is that both methods now have the same name, under the same promise.
One function, any type that keeps the promise
struct Player { name: String, number: u32, team: String } struct Team { name: String, wins: u32, losses: u32 } trait Describe { fn describe(&self) -> String; } impl Describe for Player { fn describe(&self) -> String { format!("#{} {}, {}", self.number, self.name, self.team) } } impl Describe for Team { fn describe(&self) -> String { format!("{} ({}-{})", self.name, self.wins, self.losses) } } fn print_card(item: &impl Describe) { println!("{}", item.describe()); } fn main() { let messi = Player { name: String::from("Messi"), number: 10, team: String::from("Inter Miami") }; let miami = Team { name: String::from("Inter Miami"), wins: 22, losses: 4 }; print_card(&messi); print_card(&miami); }
&impl Describe reads as "a reference to anything that implements Describe." The function doesn't care which type it got. It only calls describe.
Activity 29, Problem 1: implement a trait on paper
Describe is the trait from the last slide. Write the impl so the program prints a 20-sided die.
struct Die { sides: u32 }
// your impl here
fn main() {
let d20 = Die { sides: 20 };
print_card(&d20);
}
Answer.
impl Describe for Die {
fn describe(&self) -> String {
format!("a {}-sided die", self.sides)
}
}
Default methods: the trait itself does some of the work
Project 3 revolves around one trait. Abridged from src/agent.rs:
trait Agent {
fn name(&self) -> String;
fn choose_move(&self, board: &Board) -> Position;
fn is_human(&self) -> bool {
false
}
}
Two methods have no body, so every new agent has to write their own.
One method with a body: is_human. That's a default method, but it can still be overridden.
Two agents from that outline
struct FirstMove;
struct Random;
impl Agent for FirstMove {
fn name(&self) -> String {
String::from("FirstMove")
}
fn choose_move(&self, board: &Board) -> Position {
board.moves()[0]
}
}
impl Agent for Random {
fn name(&self) -> String {
String::from("Random")
}
fn choose_move(&self, board: &Board) -> Position {
// pick any legal move
}
}
Neither one writes is_human (so both give false by default).
Your agent for checkpoint 2 is one more impl Agent for block.
Activity 29, Problem 2: defaults, on paper
What does this print? Then add a Safety (worth 2 points) that uses the default label.
trait Scorer {
fn points(&self) -> u32;
fn label(&self) -> String {
format!("{} points", self.points())
}
}
struct Touchdown;
struct FieldGoal;
impl Scorer for Touchdown {
fn points(&self) -> u32 { 6 }
}
impl Scorer for FieldGoal {
fn points(&self) -> u32 { 3 }
fn label(&self) -> String { String::from("three, kicked") }
}
fn main() {
println!("{}", Touchdown.label());
println!("{}", FieldGoal.label());
}
Answer. It prints 6 points, then three, kicked. Touchdown never wrote label, so it gets the default from the trait.
struct Safety;
impl Scorer for Safety {
fn points(&self) -> u32 { 2 }
}
We've been using traits since September
#[derive(Debug)]
struct Card { rank: u32, suit: char }
println!("{:?}", card);
{:?} only works on types that implement a trait called Debug. #[derive(Debug)] has been implementing it for you.
Same for .clone(), ==, <, and {}. Each one is a trait. Let's look at what we've been deriving.
Debug is a trait
trait Debug {
fn fmt(&self, f: &mut Formatter) -> Result;
}
That's it! That's the Debug trait.
Here it is written by hand, for an enum:
use std::fmt;
enum Suit { Hearts, Diamonds, Clubs, Spades }
impl fmt::Debug for Suit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Suit::Hearts => write!(f, "Hearts"),
Suit::Diamonds => write!(f, "Diamonds"),
Suit::Clubs => write!(f, "Clubs"),
Suit::Spades => write!(f, "Spades"),
}
}
}
println!("{:?}", Suit::Hearts); // Hearts
#[derive(Debug)] writes exactly this for you. You almost never write it yourself.
Display is the one you write yourself
Display is Debug's cousin, for printing with just {}. Here's the whole trait:
trait Display {
fn fmt(&self, f: &mut Formatter) -> Result;
}
Same method, same signature. {:?} calls Debug's fmt, and {} calls Display's.
There's no derive for Display, because Rust can't guess what a user should see:
use std::fmt; #[derive(Debug)] enum Suit { Hearts, Diamonds, Clubs, Spades } impl fmt::Display for Suit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let symbol = match self { Suit::Hearts => "♥", Suit::Diamonds => "♦", Suit::Clubs => "♣", Suit::Spades => "♠", }; write!(f, "{}", symbol) } } fn main() { let s = Suit::Hearts; println!("{:?}", s); // Hearts println!("{}", s); // ♥ }
Debug,{:?}: for you, while debugging. You typically derive itDisplay,{}: for the user. You typically write it (or skip it)
Clone and PartialEq are also traits
trait Clone {
fn clone(&self) -> Self;
}
trait PartialEq {
fn eq(&self, other: &Self) -> bool;
}
Both are derivable with the defaults you'd expect:
#[derive(Debug, Clone, PartialEq)]
struct Card { rank: u32, suit: char }
let a = Card { rank: 7, suit: 'h' };
let b = a.clone(); // Clone
println!("{}", a == b); // PartialEq: true
Derived PartialEq compares field by field. Derived Clone clones field by field.
So what does #[derive(...)] do?
It's a macro: code that writes code. The compiler generates an impl block for each trait you name.
// What you write:
#[derive(Debug, Clone, PartialEq)]
struct Card { rank: u32, suit: char }
// What the compiler writes for you:
impl Debug for Card { /* fmt, printing each field */ }
impl Clone for Card {
fn clone(&self) -> Self {
Card { rank: self.rank.clone(), suit: self.suit.clone() }
}
}
impl PartialEq for Card {
fn eq(&self, other: &Self) -> bool {
self.rank == other.rank && self.suit == other.suit
}
}
Sorting is a trait too
#[derive(Debug)] struct Striker { name: String, goals: u32 } fn main() { let mut scores = vec![31, 7, 24, 14]; scores.sort(); println!("{:?}", scores); let mut names = vec![String::from("Messi"), String::from("Haaland"), String::from("Mbappé")]; names.sort(); println!("{:?}", names); let mut strikers = vec![ Striker { name: String::from("Messi"), goals: 20 }, Striker { name: String::from("Haaland"), goals: 27 }, Striker { name: String::from("Mbappé"), goals: 31 }, ]; strikers.sort(); println!("{:?}", strikers); }
error[E0277]: the trait bound `Striker: Ord` is not satisfied
Numbers sort. Strings sort, alphabetically. Strikers don't (yet).
sort only works on types that implement a trait called Ord, and we haven't told Rust how to put two strikers in order. (By name? By goals?)
When the compiler says "the trait Ord is not satisfied," it's telling you you need to implement Ord to get it to work.
Ord is a trait
trait Ord {
fn cmp(&self, other: &Self) -> Ordering;
}
enum Ordering { Less, Equal, Greater }
cmp means you compare yourself to another value of the same type, and answer with one of three variants.
7.cmp(&12) // Less
String::from("Messi").cmp(&String::from("Haaland")) // Greater
sort calls cmp on pairs of elements until everything's in order. That's all it needs from a type.
We could derive it. Derived Ord compares field by field, in the order the fields are declared, so strikers would sort by name. We want goals, so we'll write it ourselves.
Activity 29, Problem 3: implement Ord on paper
Write impl Ord for Striker so that strikers.sort() puts the fewest goals first. u32 already knows how to cmp.
Ord needs Eq too, which is like PartialEq but also needs every value to equal itself.
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq)]
struct Striker { name: String, goals: u32 }
// your impl Ord here
// Rust also wants PartialOrd. It just asks Ord:
impl PartialOrd for Striker {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
If you have time: what one change puts the most goals first?
Answer.
impl Ord for Striker {
fn cmp(&self, other: &Self) -> Ordering {
self.goals.cmp(&other.goals)
}
}
The body hands the job to u32's own cmp. Writing it out with if self.goals < other.goals { Ordering::Less } ... works too. For most goals first, swap the two sides: other.goals.cmp(&self.goals).
One collection, several types
Project 3 will end with a tournament where everyone submits a player agent and they all play each other.
To do that, we need one big vec holding agents that are of different types:
struct Random;
struct Minimax { depth: u32 }
let field = vec![Random, Minimax { depth: 3 }];
So what type is field?
Answer. There isn't one (and can't be). vec! needs every element to be the same type, and Random and Minimax are two different types.
Let's try the obvious...
Both types implement Agent, so let's ask for a vector of those:
trait Agent { fn name(&self) -> String; } struct Random; struct Minimax { depth: u32 } impl Agent for Random { fn name(&self) -> String { String::from("Random") } } impl Agent for Minimax { fn name(&self) -> String { format!("Minimax (depth {})", self.depth) } } fn main() { let field: Vec<Agent> = vec![Random, Minimax { depth: 3 }]; for agent in &field { println!("{}", agent.name()); } }
error[E0782]: expected a type, found a trait
help: you can add the `dyn` keyword if you want a trait object
Agent is a promise about types. Random and Minimax are the types. The compiler even hands you the keyword.
So let's take the compiler's advice?
let field: Vec<dyn Agent> = vec![Random, Minimax { depth: 3 }];
We get another error:
error[E0277]: the size for values of type `dyn Agent` cannot be known at compilation time
= help: the trait `Sized` is not implemented for `dyn Agent`
note: required by an implicit `Sized` bound in `Vec`
A Vec lays its elements out end to end, so it has to know how big one element is (even though it's on the heap). dyn Agent might be a Random with no data, a Minimax with a depth, or something custom and big.
It's the same reason a Vec<String> doesn't hold the text itself. Every string is a different length, so the Vec holds fixed-size handles that point to the heap.
So the fix is the same as it was for Vec<String>
Put the value on the heap and hold a pointer to it. A pointer has a size the compiler knows:
fn main() {
let field: Vec<Box<dyn Agent>> = vec![
Box::new(Random),
Box::new(Minimax { depth: 3 }),
];
for agent in &field {
println!("{}", agent.name());
}
}
That compiles, and the loop calls the right name() for each one. Box<dyn Agent> is a trait object: a box holding something that keeps the Agent promise.
What's inside a Box<dyn Agent>?
A Random has no fields. A Minimax has a depth. The loop called agent.name() on both and got the right answer each time. How?
The box has to carry two things:
- the data: the fields of whichever struct is in there
- the methods: which
nameand whichchoose_movego with that struct
So it holds a pointer to each. Here's one box on its own:
let agent: Box<dyn Agent> = Box::new(Minimax { depth: 3 });
Stack: Heap:
┌───────────────────────────┐
│ main() │ ┌──────────────┐
│ └ agent: Box<dyn Agent> │ │ Minimax │
│ ├ data ────────────────┼────────▶│ └ depth: 3 │
│ └ methods ─────────────┼───┐ └──────────────┘
└───────────────────────────┘ │
│ Program binary (read-only):
│ ┌───────────────────────────┐
└────▶│ Agent methods for Minimax │
│ ├ name │
│ └ choose_move │
└───────────────────────────┘
Calling agent.name() follows the methods pointer to find the right name, while the program runs. That's called dynamic dispatch.
Vec<Box<dyn Agent>> is the shape to remember. The tournament in Project 3 is round_robin(agents: &[Box<dyn Agent>], ...): 73 strategies, 73 types, one slice.
The table-of-methods picture is in the appendix at the bottom of this page.
Activity 29
See Activity 29. Problems 1 to 3 are done. Problem 4 is on a laptop: one Shape trait, two shapes, one Vec<Box<dyn Shape>>, then a third shape added without touching the loop. Answers go on Gradescope.
Appendix: three things we skipped
Trait extension
One trait can require another. Employee: Person means "to implement Employee, you must also implement Person," and Employee's default methods can call Person's methods:
trait Person {
fn get_name(&self) -> String;
}
trait Employee: Person {
fn employee_id(&self) -> u32;
fn badge(&self) -> String {
format!("{} - #{}", self.get_name(), self.employee_id())
}
}
A type implements both, in two impl blocks, the base trait first. You'll see this in the standard library: Eq: PartialEq and Ord: PartialOrd + Eq, which is why deriving Ord needs the other three.
Which traits need a use
Some traits are in the prelude, so they work without importing anything: Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Drop, Iterator. Deriving them needs no use line either.
Others have to be brought in:
use std::fmt::{Debug, Display};
use std::ops::{Add, Sub, Mul, Div};
#[derive(Debug)] works without the use because the derive macro writes the full path itself. Writing impl Display for by hand is where you first need use std::fmt.
The table of methods behind Box<dyn Agent>
┌─ Box<dyn Agent> holding a Minimax ──────┐
│ │
│ The box is two pointers │
│ ├─ data_ptr ──────────────┐ │
│ └─ vtable_ptr ────┐ │ │
└──────────────────────┼───────┼──────────┘
│ │ ┌──────────────────────────┐
│ └──▶│ Minimax { │
│ │ depth: 3, │
│ │ } │
│ └──────────────────────────┘
└─▶ vtable for Agent on Minimax (in the binary):
┌────────────────────────────────┐
│ name: 0x1234 │
│ choose_move: 0x5678 │
│ is_human: 0xABCD │
│ drop: 0xDEF0 │
└────────────────────────────────┘
When you call agent.name(): follow the vtable pointer, look up the name entry, call that function with the data pointer. The vtable is built once per (type, trait) pair when the program is compiled; only the lookup happens at run time.
That lookup is what dynamic dispatch costs: two pointer hops on every call. Wednesday's generics are the other choice.
- Trait objects (
Box<dyn Trait>): a little slower, and you can mix types in one collection - Generics: no cost per call, and every element has to be the same type
Lecture 30 - Generics: one function, many types
Announcements
Learning objectives
By the end of today, you should be able to:
- Write generic functions and structs using type parameters
- Use trait bounds to say what a generic type has to be able to do
- Explain what the compiler does with a generic function, and why it costs nothing at run time
- Recognize the generics we've been using all along
Warm-up: name a trait
Consider: a dog, a goldfish, a parrot.
🐕 🐟 🦜
Try to name a trait that two of them have and the third doesn't.
Now a function: take_for_a_walk(pet). Which of the three can I call it on?
Put this on a map
I have a function that puts a thing on a map. Which of these should I be able to call it on?
- a street address
- a building name, like Warren Towers
- a latitude and longitude
- a person
- a photo
- a ZIP code
- a phone number
- a pizza
Think, then pair. Which ones work, and what do those things have in common?
Sort this pile
Same two questions, for a function that sorts a pile:
- a hand of playing cards
- a shelf of books
- a jar of coins
- a stack of receipts
- a waiting room of patients at the ER
- a team of soccer players
- a bag of marbles
Here's the idea: every function, implicitly, has a list like this.
Python never makes it explicit, so you only find out you're a pizza when the code bugs out.
Rust makes you specify what you need in the signature, and then the function works on everything that meets it.
One max, many types
In Python, one function handles every type we throw at it:
def max(x, y):
return x if x > y else y
>>> max(3, 2)
3
>>> max(3.1, 2.2)
3.1
>>> max('s', 't')
't'
From the pre-work: how do you think Rust does this?
What Python's flexibility costs
- Python works out what
>means for these two values every time the function is called, while the program runs - A bad call isn't caught until that line runs
>>> max(3, 'a')
TypeError: '>' not supported between instances of 'int' and 'str'
Rust without generics
Every parameter in Rust has a type, so with what we know so far it's one function per type:
fn max_i32(x: i32, y: i32) -> i32 { if x > y { x } else { y } } fn max_f64(x: f64, y: f64) -> f64 { if x > y { x } else { y } } fn max_char(x: char, y: char) -> char { if x > y { x } else { y } } fn main() { println!("{}", max_i32(3, 8)); // 8 println!("{}", max_f64(3.3, 8.1)); // 8.1 println!("{}", max_char('a', 'b')); // b }
Every call is checked before the program runs. But supporting N types = writing N functions, all with the same body.
We want Python's one function with Rust's early checking. That's what generics are for.
A first generic function
fn passit<T>(x: T) -> T { x } fn main() { let x = passit(5); println!("x is {}", x); // x is 5 let x = passit(1.1); println!("x is {}", x); // x is 1.1 let x = passit('s'); println!("x is {}", x); // x is s }
The <T> after the name makes the function generic. T is a placeholder for a type, filled in at each call: i32, then f64, then char.
This one works because it does nothing with x except hand it back.
T is only a name, short for "type". You'll also see U for a second type, E for an error type, and K and V for keys and values on Friday.
Okay, but that was pretty boring...
Let's write the one we wanted:
fn max<T>(x: T, y: T) -> T { if x > y { x } else { y } } fn main() { println!("{}", max(5, 10)); }
error[E0369]: binary operation `>` cannot be applied to type `T`
help: consider restricting type parameter `T` with trait `PartialOrd`
T could be any type at all, and plenty of types have no >. On Monday, Striker didn't. Rust won't let a generic function do something only some types can do.
Trait bounds: say what T has to be able to do
fn max<T: PartialOrd>(x: T, y: T) -> T { if x > y { x } else { y } } #[derive(Debug, PartialEq)] struct Striker { goals: u32, name: String } fn main() { println!("{}", max(5, 10)); // T = i32 println!("{}", max(3.14, 2.7)); // T = f64 println!("{}", max('a', 'b')); // T = char let messi = Striker { goals: 20, name: String::from("Messi") }; let haaland = Striker { goals: 27, name: String::from("Haaland") }; // println!("{:?}", max(messi, haaland)); }
T: PartialOrd is a trait bound. It reads as "any type T, as long as it implements PartialOrd."
Inside the function we can use exactly what the bound promises. The compiler works out T at each call from the arguments.
Write the body first and let the compiler name the bound. Its help line said "consider restricting type parameter T with trait PartialOrd", and that was the whole fix.
Monday's &impl Trait was this in disguise
// Monday
fn print_card(item: &impl Describe) {
println!("{}", item.describe());
}
// The same function, written out
fn print_card<T: Describe>(item: &T) {
println!("{}", item.describe());
}
Both say: a reference to any type that implements Describe.
&impl Traitis shorter, and fine for one parameter<T: Trait>gives the type a name. We need the name when two things have to be the same type, like thexandyinmax
Activity 30, Problem 1: keep both
See Problem 1 on Activity 30.
Answer. Three things change, and each one forces the next:
fn max<T: PartialOrd + Clone>(x: &T, y: &T) -> T {
if *x > *y { x.clone() } else { y.clone() }
}
let bigger = max(&a, &b); // a and b are only borrowed
- Borrow the arguments:
&Tin the signature,&aand&bat the call - A borrowed
xcan't be handed back as an ownedT, so return a clone .clone()only gives back aTwhenTisClone, so add the bound
What the compiler does with a generic function
It looks at every call, sees which types T gets, and writes a separate copy of the function for each one.
// What we write:
fn max<T: PartialOrd>(x: T, y: T) -> T {
if x > y { x } else { y }
}
fn main() {
println!("{}", max(5, 10));
println!("{}", max(3.14, 2.7));
}
// What the compiler generates (roughly):
fn max_i32(x: i32, y: i32) -> i32 {
if x > y { x } else { y }
}
fn max_f64(x: f64, y: f64) -> f64 {
if x > y { x } else { y }
}
fn main() {
println!("{}", max_i32(5, 10));
println!("{}", max_f64(3.14, 2.7));
}
That's the code we wrote by hand at the start of class. The compiler wrote it for us.
The name for this is monomorphization. max<T> is polymorphic (many shapes), and each compiled copy is monomorphic (one shape).
Generic structs
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
let int_point = Point { x: 5, y: 10 }; // Point<i32>
let float_point = Point { x: 3.14, y: 2.7 }; // Point<f64>
Point<i32> and Point<f64> are two different types, with different sizes:
Stack:
┌────────────────────────────────┐
│ main() │
│ ├ int_point: Point<i32> │
│ │ ├ x: i32 = 5 │ 4 bytes
│ │ └ y: i32 = 10 │ 4 bytes
│ └ float_point: Point<f64> │
│ ├ x: f64 = 3.14 │ 8 bytes
│ └ y: f64 = 2.7 │ 8 bytes
└────────────────────────────────┘
Methods on generic structs
#[derive(Debug)] struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn new(x: T, y: T) -> Point<T> { Point { x, y } } fn get_x(&self) -> &T { &self.x } } fn main() { let point1 = Point::new(1, 2); // Point<i32> let point2 = Point::new(1.5, 2.5); // Point<f64> println!("{}", point1.get_x()); println!("{}", point2.get_x()); }
impl<T> introduces the name T, and Point<T> uses it. These methods exist for every Point, whatever T is.
The bounds we'll use most
use std::fmt::Debug; // Debug: can be printed with {:?} fn debug_value<T: Debug>(val: T) { println!("Value: {:?}", val); } // Clone: can be duplicated with .clone() fn duplicate<T: Clone>(val: &T) -> T { val.clone() } // Copy: copied automatically, never moved fn two_of<T: Copy>(val: T) -> (T, T) { (val, val) } fn main() { debug_value(vec![1, 2]); println!("{}", duplicate(&String::from("hi"))); println!("{:?}", two_of(7)); }
Naming Debug in a bound needs use std::fmt::Debug;, even though #[derive(Debug)] never did. Forget it and the error is "expected trait, found derive macro Debug".
Clone, Copy, PartialEq, and PartialOrd need no use.
More than one bound: + and where
use std::fmt::Debug;
fn show_larger<T: PartialOrd + Debug>(x: T, y: T) {
if x > y {
println!("{:?}", x);
} else {
println!("{:?}", y);
}
}
The same function, with the bounds moved to a where clause:
fn show_larger<T>(x: T, y: T)
where
T: PartialOrd + Debug,
{
if x > y {
println!("{:?}", x);
} else {
println!("{:?}", y);
}
}
where reads better once there are several bounds, or several type parameters.
We've been using generics all along
let maybe_number: Option<i32> = Some(42);
let outcome: Result<i32, String> = Ok(42);
let numbers: Vec<i32> = vec![1, 2, 3];
let boxed: Box<i32> = Box::new(5);
Now we know what the angle brackets mean. Here's how the standard library defines two of them:
enum Option<T> {
None,
Some(T),
}
enum Result<T, E> {
Ok(T),
Err(E),
}
Option<i32> is that enum with T filled in as i32. Result<i32, String> holds an i32 on success and a String on error.
Zero-cost abstractions
On Monday, a Box<dyn Agent> found the right name() while the program ran: follow a pointer, look up the method, call it. That lookup happens on every call.
A generic function has nothing to look up. By the time the program runs, max(5, 10) is already a call to the i32 copy.
Generics, <T: Trait> | Trait objects, Box<dyn Trait> | |
|---|---|---|
| Which code runs is decided | when compiling | while running |
| Cost per call | none | one lookup |
Mixed types in one Vec | no | yes |
"What you don't use, you don't pay for. What you do use, you couldn't hand code any better."
Bjarne Stroustrup, about C++ (but applies to Rust!)
E.g. Vec<T> is as fast as an array written by hand for one type.
A few weeks ago we said Rust moved the cost from run time to your time. Generics are the same trade: you and the compiler do more work up front, and the running program does less.
Activity 30
See Activity 30. Problem 1 is done, so start at Problem 2.
Appendix: methods that only exist for some types
Type-specific implementations
We can also write methods for one specific T:
#[derive(Debug)] struct Point<T> { x: T, y: T, } // Works for any type T impl<T> Point<T> { fn new(x: T, y: T) -> Point<T> { Point { x, y } } } // Only for Point<i32> impl Point<i32> { fn distance_from_origin(&self) -> f64 { ((self.x.pow(2) + self.y.pow(2)) as f64).sqrt() } } // Only for Point<f64> impl Point<f64> { fn distance_from_origin(&self) -> f64 { (self.x.powi(2) + self.y.powi(2)).sqrt() } } fn main() { let int_point = Point::new(3, 4); println!("Distance: {}", int_point.distance_from_origin()); // 5 let float_point = Point::new(3.0, 4.0); println!("Distance: {}", float_point.distance_from_origin()); // 5 // let char_point = Point::new('a', 'b'); // char_point.distance_from_origin(); }
- Some methods only make sense for certain types. What's the distance from the origin to
('a', 'b')? Uncomment the twochar_pointlines and run: "no method nameddistance_from_originfound for structPoint<char>" - Different types sometimes need different code:
powfor integers,powifor floats
Trait bounds on methods
Some methods only make sense for some types. Let's write one that swaps x and y:
#[derive(Debug)] struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn new(x: T, y: T) -> Point<T> { Point { x, y } } fn swap(&mut self) { let temp = self.x; self.x = self.y; self.y = temp; } } fn main() { let mut point = Point::new(2, 3); point.swap(); println!("{:?}", point); }
error[E0507]: cannot move out of `self.x` which is behind a mutable reference
We've seen this error before. self is borrowed, so we can't move a value out of it.
If T is i32, let temp = self.x is a copy and everything's fine. If T is String, it's a move. The compiler has to assume T could be either.
Put the bound on the impl
#[derive(Debug)] struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn new(x: T, y: T) -> Point<T> { Point { x, y } } } // swap only exists for types that are Copy impl<T: Copy> Point<T> { fn swap(&mut self) { let temp = self.x; // a copy, since T is Copy self.x = self.y; self.y = temp; } } fn main() { let mut point = Point::new(2, 3); println!("{:?}", point); // Point { x: 2, y: 3 } point.swap(); println!("{:?}", point); // Point { x: 3, y: 2 } }
impl<T: Copy> means "these methods only exist when T is Copy." A Point<i32> can swap. A Point<String> can't, and the compiler says so.
(The compiler's own suggestion was Clone, which also works, with a .clone() on each line.)
Lecture 31 - Hashing: HashMap, HashSet
Announcements
Learning objectives
By the end of today, you should be able to:
- Use
HashSet<T>to check membership and find unique values - Explain what a hash function does, and how a key becomes a bucket index
- Read
HashMap<K, V>code that inserts, looks up, counts, and iterates - Explain how a site checks a password without ever storing it, and what a weak hash costs
- Say what
insert,get, andcontainscost, and why they beat searching aVec - Draw a
HashMapon the stack and the heap
That username is taken
You pick a username on a site with a billion accounts. The moment you finish typing, it tells you the name is taken.
How did it check them all that fast?
Lay out the cards
Imagine this: I hand you 1,000 index cards, each with a name on it (first and last). In a minute I'll call out a name, and the faster you can find the card the more money I'll give you.
You have a table and five minutes to get ready. How do you lay them out?
Think/pair/share
The solution: hashes
A hash function takes any input and turns it into a number.
- Deterministic: the same input always gives the same number
- Fast: a few nanoseconds for a short string
- Uniform: spreads inputs evenly across the range
- Avalanche: a tiny change in the input changes the whole output
hash("Alice")= 63350368hash("alice")= 92903040
- Hard to invert, for the good ones: given the number, you can't recover the input. (Question - why would this matter?)
A toy hash function
A simplified one, to show the idea. Real ones are much more careful.
fn toy_hash(s: &str) -> u64 { let mut hash: u64 = 0; for ch in s.chars() { hash = hash.wrapping_mul(31).wrapping_add(ch as u64); } hash } fn main() { println!("{}", toy_hash("Alice")); println!("{}", toy_hash("Bob")); // println!("{}", toy_hash("alice")); }
Multiply, add, multiply, add. Every character shifts everything that came before it, which is where the avalanche comes from.
What does Rust use? By default, SipHash 1-3. Slower than the toy, and built so that nobody can feed your program keys chosen to collide on purpose. Have fun going down that rabbit hole.
So what do we do with the hash?
Every key is now a number, and the numbers are spread evenly. Can we use the number as the shelf?
hash("Alice") = 63350368, so Alice goes on shelf 63,350,368. A u64 goes up to about , so that's shelves for 1,000 cards, and nearly all of them empty.
So we pick how many shelves we can afford, say 8, and fold every hash onto them with modulo:
hash("Alice") % 8 = 63350368 % 8 = 0
hash("Bob") % 8 = 66965 % 8 = 5
[0] [1] [2] [3] [4] [5] [6] [7]
Alice Bob
Each shelf is a bucket, and the number the modulo gives is its bucket index. The hashes are spread evenly, so the buckets fill evenly too: no 20-deep A pile, and no empty Q pile.
A lookup is three steps
That's the whole machine: a hash function, plus one array of buckets on the heap. To find a key:
- Hash the key
- Modulo to get a bucket index
- Go straight to that bucket and compare the key
Three steps. The number of steps doesn't depend on how many keys are stored. A billion or ten, same three steps.
We'll draw the array in full once there are values in it. First, let's build one.
Activity 31, Round 1: everyone to your bucket
The room is the hash table. Eight buckets on the walls, 0 to 7. Your key is your first name.
hash(name) = value of the first letter, A is 1 through Z is 26. Bucket = hash % 8.
| Bucket | First letter |
|---|---|
| 0 | H P X |
| 1 | A I Q Y |
| 2 | B J R Z |
| 3 | C K S |
| 4 | D L T |
| 5 | E M U |
| 6 | F N V |
| 7 | G O W |
Go. Then write your bucket, the longest pile, and the empty buckets on your sheet.
When two keys land in the same bucket
With 8 buckets and 9 keys, two of them share a bucket. That's a collision, and it happens all the time.
The fix is simple: if the bucket's taken by a different key, look in the next one. Keep going until you find the key or hit an empty bucket.
hash("Alice") % 8 = 0 bucket [0]: Alice found
hash("Erin") % 8 = 0 bucket [0]: Alice taken by Alice
bucket [1]: Erin found
hash("Zed") % 8 = 0 bucket [0]: Alice no
bucket [1]: Erin no
bucket [2]: empty stop: Zed isn't here
Collisions cost extra comparisons. Too many and the table slows to a crawl, so it grows before it fills up: at about 7/8 full it doubles the bucket array and re-places every key.
That's why there's always an empty bucket to stop a search at.
Let's watch it grow
use std::collections::HashSet; // std doesn't report the bucket count, but it's always the next power // of two that keeps the table at most 7/8 full fn buckets(cap: usize) -> usize { if cap == 0 { 0 } else if cap < 4 { 4 } else if cap < 8 { 8 } else { (cap * 8 / 7).next_power_of_two() } } fn main() { let mut seen: HashSet<i32> = HashSet::new(); println!("len {:>2}, cap {:>2}, buckets {:>2}", seen.len(), seen.capacity(), buckets(seen.capacity())); for i in 1..=15 { seen.insert(i); println!("len {:>2}, cap {:>2}, buckets {:>2}", seen.len(), seen.capacity(), buckets(seen.capacity())); } }
We drew this for Vec a few weeks ago: when push runs out of room, it doubles, copies everything across, and frees the old block. The hash table does the same, with one extra step: every key gets re-hashed, because % 8 just became % 16.
The thing we just built is a HashSet
A bucket array, a hash function, and your keys in the buckets. In Rust that's HashSet<T>: a collection of unique values, on the heap, that answers "is this in here?"
(Yep, it's a Python set.)
use std::collections::HashSet; fn main() { let mut taken = HashSet::new(); taken.insert("alice_smith".to_string()); taken.insert("bob_j".to_string()); taken.insert("carol_w".to_string()); // The username check. No loop. if taken.contains("rustacean_99") { println!("taken"); } else { println!("available"); } }
.contains() is hash, modulo, compare. Three steps whether the set holds three names or a billion.
What can be a T?
The compiler has to hash the key and compare it to the one in the bucket. So the type has to promise it can do both:
use std::collections::HashSet; #[derive(Debug)] struct Striker { goals: u32, name: String } fn main() { let mut squad = HashSet::new(); squad.insert(Striker { goals: 27, name: String::from("Haaland") }); println!("{:?}", squad); }
error[E0277]: the trait bound `Striker: Eq` is not satisfied
note: required by a bound in `HashSet::<T, S, A>::insert`
| T: Eq + Hash,
That's a trait bound, written by the standard library: insert works for any T with Eq and Hash. Both are traits you can derive, the same way we derived traits on Monday:
#[derive(Debug, PartialEq, Eq, Hash)]
struct Striker { goals: u32, name: String }
Numbers, char, String, and &str all have them already. Every key in a HashMap needs them too.
Pour a Vec in, and the duplicates vanish
You have a customer list, and some customers appear more than once:
use std::collections::HashSet; fn main() { let customers = vec!["Alice", "Bob", "Alice", "Carol", "Bob", "David", "Alice"]; // Pour the Vec into a HashSet. Duplicates vanish on the way in. let unique_customers: HashSet<&str> = customers.iter().cloned().collect(); println!("Original list: {} customers", customers.len()); // 7 println!("Unique customers: {}", unique_customers.len()); // 4 for customer in &unique_customers { println!("Customer: {}", customer); } }
.collect() builds whatever collection the type annotation asks for. Here that's a HashSet<&str>, so inserting a name that's already there does nothing.
.iter().cloned() copies each item in and leaves the Vec alone. .into_iter() would move the items in instead, and the Vec would be gone. The appendix has the two side by side.
What each one costs
Most operations are cheap, and once in a while one is expensive. The word for "expensive rarely, free the rest of the time, cheap on average" is amortized.
A Vec with n elements:
| Operation | Cost | Why |
|---|---|---|
vec[i] | O(1) | Pointer plus offset |
vec.push(x) | O(1) amortized | Usually one write. Every doubling, a copy of n |
vec.pop() | O(1) | Decrement len |
vec.insert(0, x) | O(n) | Shift everything right |
vec.contains(&x) | O(n) | Look at every element until found |
A HashSet with n keys:
| Operation | Cost | Why |
|---|---|---|
set.contains(&x) | O(1) average | Hash, modulo, compare. A few extra on a collision |
set.insert(x) | O(1) amortized | Same, plus the occasional doubling and re-hash |
set.remove(&x) | O(1) average | Same |
The one Vec can't do in O(1) is the one HashSet is for: asking is this thing here?
So which is faster?
You run a game with 100,000 registered player IDs. 10,000 match results come in, and you need to know which ones belong to registered players.
// Option A: the IDs in a Vec
let players_vec = vec![/* 100,000 player IDs */];
for result in results.iter() {
if players_vec.contains(&result.player_id) {
// count it
}
}
// Option B: the IDs in a HashSet
let players_set: HashSet<_> = player_ids.into_iter().collect();
for result in results.iter() {
if players_set.contains(&result.player_id) {
// count it
}
}
Which is faster? How much faster?
They look the same. The difference is what contains does:
Vec::containsmay look at all 100,000 IDs for each result. 100,000 times 10,000 = a billion comparisonsHashSet::containshashes the ID and checks one bucket. 10,000 lookups
Now staple a value to each card
Back at the table of names, imagine writing a phone number on every name card.
Same piles, but now the question is what a person's phone number is.
That's a HashMap<K, V>: the same bucket array, with a value stored next to each key.
(Yep, it's a Python dict.)
use std::collections::HashMap; fn main() { // A phone book, from name to number let mut customer_data = HashMap::new(); customer_data.insert("Alice Smith".to_string(), 12345); customer_data.insert("Bob Jones".to_string(), 56789); customer_data.insert("Carol White".to_string(), 11235); // Look Alice up. No loop. match customer_data.get("Alice Smith") { Some(number) => println!("Alice's number is {}", number), None => println!("Alice not found"), } }
.get() returns an Option, because the key might not be there. Same three steps as the set, so the same costs: get, insert, and contains_key are all O(1) average.
customer_data["Alice Smith"] also works, but it panics if the key is missing. Use .get() unless you're certain.
Memory layout: the whole picture
let mut customer_data = HashMap::new();
customer_data.insert("Alice Smith".to_string(), 12345);
customer_data.insert("Bob Jones".to_string(), 56789);
Stack: Heap: the bucket array More heap: the keys
┌────────────────────────┐ ┌───┬────────────────────────┐
│ main() │ │ 0 │ empty │
│ └ customer_data: │ ├───┼────────────────────────┤
│ HashMap<String,i32> │ │ 1 │ key: String │ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ ├ ptr ──────────────┼───▶│ │ ├ ptr ────────────────┼───▶│ B │ o │ b │ │ J │ o │ n │ e │ s │
│ ├ len: 2 │ │ │ ├ len: 9 │ └───┴───┴───┴───┴───┴───┴───┴───┴───┘
│ └ cap: 3 │ │ │ └ cap: 9 │
└────────────────────────┘ │ │ value: i32 = 56789 │
├───┼────────────────────────┤
│ 2 │ empty │
├───┼────────────────────────┤
│ 3 │ key: String │ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ │ ├ ptr ────────────────┼───▶│ A │ l │ i │ c │ e │ │ S │ m │ i │ t │ h │
│ │ ├ len: 11 │ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
│ │ └ cap: 11 │
│ │ value: i32 = 12345 │
└───┴────────────────────────┘
Stack: Heap: the bucket array More heap: the keys
┌─────────────────────┐ ┌───┬─────────────────────┐
│ main() │ │ 0 │ empty │
│ └ customer_data: │ ├───┼─────────────────────┤
│ HashMap<String, │ │ 1 │ key: String │
│ i32> │ │ │ ├ ptr ─────────────┼───▶ "Bob Jones"
│ ├ ptr ───────────┼───▶│ │ ├ len: 9 │
│ ├ len: 2 │ │ │ └ cap: 9 │
│ └ cap: 3 │ │ │ value: i32 = 56789 │
└─────────────────────┘ ├───┼─────────────────────┤
│ 2 │ empty │
├───┼─────────────────────┤
│ 3 │ key: String │
│ │ ├ ptr ─────────────┼───▶ "Alice Smith"
│ │ ├ len: 11 │
│ │ └ cap: 11 │
│ │ value: i32 = 12345 │
└───┴─────────────────────┘
- The handle on the stack is the same shape as
Vec's: a pointer, a length, a capacity - The bucket array is on the heap. Each bucket holds one key and one value, or is empty
- The keys are
Strings, so each one is a handle pointing at its own letters, further out on the heap - Which bucket a pair lands in is the hash of its key, modulo the bucket count
- Four buckets and
cap: 3: it grows before it's full, so there's always an empty bucket to stop a search at - A
HashSetis this picture without thevaluerows
HashMap: the methods you'll read
Be able to read these. You don't have to write them from memory.
use std::collections::HashMap; fn main() { let mut prices: HashMap<String, f64> = HashMap::new(); prices.insert("bat".to_string(), 30.0); // add, or overwrite if the key's there prices.insert("glove".to_string(), 45.0); println!("{:?}", prices.get("bat")); // Some(30.0), or None if it's missing println!("{}", prices.contains_key("helmet")); // false prices.remove("glove"); // takes the pair out for (item, price) in &prices { // references, in random order println!("{item}: {price}"); } // Counting: find the slot, put 0 there if it's empty, add 1 through the &mut let mut counts: HashMap<&str, u32> = HashMap::new(); for word in "the cat sat on the mat".split_whitespace() { *counts.entry(word).or_insert(0) += 1; } println!("{:?}", counts); }
The order is random, and changes from one run to the next. It's whatever order the buckets happen to be in. Never write a test that depends on the order of a hashmap or hashset (or a Python dict or set). If you need an order, collect the keys into a Vec and sort.
Think-pair-share: what happens here?
use std::collections::HashMap; fn main() { let product = String::from("smartphone"); let mut prices = HashMap::new(); prices.insert(product, 599.99); println!("Product: {}", product); }
Answer. It doesn't compile: "borrow of moved value: product".
insert takes its arguments in, so the String moved into the hashmap. If we need product afterwards, insert product.clone().
Storing passwords
A site has to check your password every time you log in. It must never store the password.
How would you use a hash function for this?
- When you sign up, the site stores
hash(password), a number - When you log in, it hashes what you typed and compares the two numbers
- The password itself is never written down anywhere
If the site's database leaks, the thief gets numbers. "Hard to invert" was on the list of properties earlier, and this is why.
Breaking in without the password
The login check compares two numbers. So the thief doesn't need your password. Any string with the same hash value gets in.
With a weak hash, that's easy. Our toy hash has only 2^64 outputs and no secret, and you'll find colliding names for an even simpler one in a few minutes.
With a strong hash it's meant to be impossible, but sometimes it stops being so. MD5 and SHA-1 were the standard for years, but both now have known collisions and are being phased out.
The everyday attack is simpler still: a good hash is fast, so a graphics card tries billions of guesses a second with common words. Sites defend with a hash built to be slow (bcrypt, Argon2) and a salt, a random string stored next to each hash, so cracking one person's password doesn't unlock everyone who chose the same one.
Rust's default hash for HashMap (and Python's for dict) are built for speed. Neither is a password-grade hash!
Activity 31, Rounds 2 to 4
See Activity 31.
Appendix: HashMap methods, the longer versions
Adding and updating
use std::collections::HashMap; fn main() { let mut prices = HashMap::new(); prices.insert("laptop".to_string(), 999.99); prices.insert("mouse".to_string(), 25.50); prices.insert("keyboard".to_string(), 75.00); // Same key again: overwrites prices.insert("laptop".to_string(), 899.99); // Only add if it isn't there yet if !prices.contains_key("tablet") { prices.insert("tablet".to_string(), 199.99); } // The same thing in one line prices.entry("tablet".to_string()).or_insert(199.99); println!("{:?}", prices); }
.entry(key) finds the slot for a key, whether or not anything's in it yet. .or_insert(value) fills it if it was empty. We'll use it for counting in a few minutes.
Iterating on a HashMap
use std::collections::HashMap; fn main() { let mut prices = HashMap::new(); prices.insert("laptop".to_string(), 999.99); prices.insert("mouse".to_string(), 25.50); prices.insert("keyboard".to_string(), 75.00); // Both are references for (product, price) in prices.iter() { println!("{}: ${:.2}", product, price); } // 10% off everything. price is &mut // you can't get mut references to the keys for (_product, price) in prices.iter_mut() { *price = *price * 0.9; } for (product, price) in prices.iter() { println!("{}: ${:.2}", product, price); } }
The order is random, and changes from one run to the next. It's whatever order the buckets happen to be in. Never write a test that depends on the order of items in a hashset/hashmap(/dict/set). If you need an order, collect the keys into a Vec and sort.
Counting things, the long way
How many times does each word appear?
use std::collections::HashMap; fn main() { let text = "the cat sat on the mat"; let mut word_counts = HashMap::new(); for word in text.split_whitespace() { let new_count = match word_counts.get(word) { Some(count) => count + 1, None => 1, }; word_counts.insert(word.to_string(), new_count); } for (word, count) in &word_counts { println!("'{}' appears {} times", word, count); } }
Counting things, with entry
use std::collections::HashMap; fn main() { let text = "the cat sat on the mat"; let mut word_counts = HashMap::new(); for word in text.split_whitespace() { let count = word_counts.entry(word.to_string()).or_insert(0); *count += 1; } for (word, count) in &word_counts { println!("'{}' appears {} times", word, count); } }
.entry().or_insert(0) gives back a mutable reference to the value, whether it was just inserted or already there. Then *count += 1 writes through it, the way we wrote through &mut references a few weeks ago.
Appendix: borrow the values, or move them
Two ways to pour a Vec into a set:
use std::collections::HashSet; fn main() { let names = vec![ String::from("Alice"), String::from("Bob"), String::from("Alice"), ]; // Option 1: clone each String. names is still usable let unique_names: HashSet<String> = names.iter().cloned().collect(); println!("Original: {:?}", names); println!("Unique: {:?}", unique_names); // Option 2: move each String into the set. names is gone let unique_names: HashSet<String> = names.into_iter().collect(); println!("Unique: {:?}", unique_names); // println!("{:?}", names); // borrow of moved value }
.iter().cloned()hands the set a copy of each element and leaves theVecalone.into_iter()hands over the elements themselves, and theVecis consumed
Same choice as always: clone and keep both, or move and keep one.
Appendix: understanding .iter().cloned().collect()
let customers = vec!["Alice", "Bob", "Alice"];
let unique: HashSet<&str> = customers.iter().cloned().collect();
Step by step:
.iter()makes an iterator over references to the elements. Each item is a&&str, a reference to a string slice.cloned()copies each item out from behind its reference.&&strbecomes&str. ForCopytypes like&strandi32this is just copying the pointer or the value.collect()gathers the items into whatever collection the type annotation names. Here that'sHashSet<&str>, so duplicates are dropped on the way in
.into_iter() in place of .iter() gives the elements themselves, and the Vec can't be used afterwards. .iter().cloned() on a Vec<String> clones every string, which is a real cost; .into_iter() moves them for free.
Appendix: BTreeMap, the sorted cousin
std::collections has a second map, BTreeMap<K, V>, with the same insert, get, and entry. The difference is how it's stored: a balanced tree with the keys in sorted order, which gives O(log n) lookups in place of O(1).
This means iterating a BTreeMap visits the keys in order, every time, and you can ask for a range: every key between "M" and "N".
BTreeSet is to BTreeMap as HashSet is to HashMap. Keys need Ord, which we met in the traits lecture, in place of Hash and Eq.
Lecture 32 - Binary heaps: a tree stored in a Vec
Announcements
Learning objectives
By the end of today, you should be able to:
- Explain what a priority queue is, and name a problem that needs one
- Trace
pushandpopon a binary heap, and say why each is O(log n) - Read a heap out of a
Vec: find a node's parent and children by arithmetic (you don't need to memorize the formulas) - Use
BinaryHeap, by derivingOrdon your own type so it knows what "biggest" means
Who's next?
From the pre-work: where in everyday life does the most urgent one go next, regardless of what order they arrived in?
The ER waiting room, again
In the generics lecture we talked about the piles we could sort, and one was a waiting room at the ER. We could sort by urgency, and then call the first one.
Except the room keeps changing:
- A new patient walks in every few minutes
- The doctor calls the next patient every few minutes
Should we keep the room sorted? Every arrival means finding their spot, which is fast, but then shifting everyone behind them down one seat: O(n).
But we don't need to keep the room sorted. We only need to be able to answer one question: who's next?
A line where the most urgent goes first is a priority queue.
A priority queue has three operations
| Operation | Meaning |
|---|---|
push(x) | Add something, with its priority |
pop() | Remove what has the highest priority |
peek() | Look at it without taking it out |
Rust has one in the standard library: BinaryHeap<T>.
use std::collections::BinaryHeap; fn main() { let mut heap = BinaryHeap::new(); heap.push(5); heap.push(10); heap.push(3); heap.push(8); println!("{}", heap.pop().unwrap()); println!("{}", heap.pop().unwrap()); }
Biggest first, every time. BinaryHeap is a max-heap: the biggest value is on top.
What's inside?
Debug printing shows us what it's storing:
use std::collections::BinaryHeap; fn main() { let mut heap = BinaryHeap::new(); heap.push(10); heap.push(30); heap.push(20); heap.push(5); println!("{:?}", heap); println!("{:?}", heap.peek()); }
The biggest is first, and the rest isn't sorted.
So it's keeping some order... less than full sorted order, but enough to make push and pop easy.
for x in &heap walks that same unsorted order. To get values in order, pop in a loop, or call heap.into_sorted_vec().
Two ways to do it with a Vec
Unsorted Vec. Push on the end. To pop the biggest, scan everything.
Sorted Vec, biggest at the end. Pop off the end. To push, find the right spot and shift everything after it.
push | pop the biggest | |
|---|---|---|
Unsorted Vec | O(1) | O(n) |
Sorted Vec | O(n) | O(1) |
| Binary heap | O(log n) | O(log n) |
Each Vec is free on one side and O(n) on the other. A binary heap is a Vec with a rule about where things go, and the rule gets both operations down to O(log n).
Important: two different "heaps"
Like "stack", the word "heap" means two completely different things.
Heap memory, from before the midterm:
- The region of memory where
String,Vec, andBoxkeep their data - Reached through pointers from the stack
- A memory-management idea
Heap data structure, today:
- A tree with a rule: every parent is at least as big as its children
- Used to build priority queues
- Nothing to do with where it lives in memory
Same word, two meanings, but context should make it clear. We'll do the same thing for "stack" on Wednesday.
More tree words
- A graph is a set of nodes with edges joining some of them.
- A tree is a graph with one node on top, the root, and every other node hanging off exactly one node above it.
A Root: the top node, no parent
/ \
B C B and C are children of A. A is their parent
/ / \
D E F Leaves: no children
- Height: how many rows
- Binary tree: at most two children per node
- Complete binary tree: every row is full except maybe the last, and the last fills left to right
A binary heap is a complete binary tree with the heap property: every parent is >= both its children.
A max-heap
42 Root is the largest
/ \
30 20 Every parent >= its children
/ \ / \
10 25 15 8 Tree is complete
/
5
Let's check each property.
Note what is not an issue: 25 is below 20 in the tree and larger than it, but 25 isn't 20's child. And siblings can be in any order. Only parent-to-child matters.
Not a max-heap:
20 30 > 20, and 30 is 20's child
/ \
30 25
Complete, or not
Complete: every row full except the last, which fills left to right.
42 42
/ \ / \
30 20 30 20
/ \ / \ /
10 25 15 25 15
Complete Not complete: a gap on the left
Why insist on this? Because a complete tree has no gaps, so its rows can be laid end to end.
The array trick
Read the tree row by row, left to right, and write it down:
Tree:
42
/ \
30 20
/ \ / \
10 25 15 8
Vec: [42, 30, 20, 10, 25, 15, 8]
Index: 0 1 2 3 4 5 6
Now every family relationship is arithmetic:
- Parent of index
i:(i - 1) / 2 - Left child of
i:2 * i + 1 - Right child of
i:2 * i + 2
Check: 30 is at index 1. Parent is (1 - 1) / 2 = 0, which is 42. Children are 3 and 4, which are 10 and 25.
Activity 32, Problem 1: read the Vec
See Problem 1 on Activity 32.
Answer.
- Indices
2 * 1 + 1 = 3and2 * 1 + 2 = 4: 25 and 30 - Index
(4 - 1) / 2 = 1: 40 - Yes. 50 >= 40, 35. 40 >= 25, 30. 35 >= 30, 15
- 50 on top; 40 and 35 under it; 25 and 30 under 40; 30 and 15 under 35
Where it lives: one block
let mut heap = BinaryHeap::new();
heap.push(10);
heap.push(30);
heap.push(20);
heap.push(5);
Stack: Heap:
┌─────────────────────────┐ ┌────┬────┬────┬────┐
│ main() │ │ 30 │ 10 │ 20 │ 5 │
│ └ heap: BinaryHeap<i32> │ └────┴────┴────┴────┘
│ ├ ptr ───────────────┼───▶ 0 1 2 3
│ ├ len: 4 │
│ └ cap: 4 │
└─────────────────────────┘
That's the Vec picture again! One handle on the stack, one block on the heap, and it doubles when it fills up. The tree is a way of reading the block. Nothing in memory has branches.
On Friday we'll build a tree the other way, with a Box for every node.
Push: 35 arrives. Now what?
Think/pair/share
The only open spot that keeps the tree complete is the end of the last row, so 35 goes there:
42
/ \
30 20
/ \ / \
10 25 15 8
/
35
[42, 30, 20, 10, 25, 15, 8, 35]
That broke the heap property: 35 is under 10. How would you fix it? What's the least work that gets us back to a heap?
Push: add, then bubble up
- Put the new value at the end of the
Vec, which is the next open spot in the last row - Compare it with its parent. If it's bigger, swap
- Repeat until the parent is bigger, or it's the root
Insert 35 into [42, 30, 20, 10, 25, 15, 8]:
Step 1: add to the end Step 2: 35 > 10, swap
42 42
/ \ / \
30 20 30 20
/ \ / \ / \ / \
10 25 15 8 35 25 15 8
/ /
35 10
[42, 30, 20, 10, 25, 15, 8, 35] [42, 30, 20, 35, 25, 15, 8, 10]
Push: keep going
Step 3: 35 > 30, swap Step 4: 35 < 42, stop
42 42
/ \ / \
35 20 35 20
/ \ / \ / \ / \
30 25 15 8 30 25 15 8
/ /
10 10
[42, 35, 20, 30, 25, 15, 8, 10] [42, 35, 20, 30, 25, 15, 8, 10]
Each swap moves the value up one row. A heap with n values has about log n rows, so that's at most log n swaps: O(log n).
Push, in code
The whole thing, on a plain Vec<i32>:
fn push(heap: &mut Vec<i32>, x: i32) { heap.push(x); // 1. add at the end let mut i = heap.len() - 1; while i > 0 { let parent = (i - 1) / 2; if heap[i] <= heap[parent] { break; } // 3. parent is bigger: stop heap.swap(i, parent); // 2. bubble up i = parent; } } fn main() { let mut heap = vec![42, 30, 20, 10, 25, 15, 8]; push(&mut heap, 35); println!("{:?}", heap); }
So BinaryHeap::push is really just a Vec with swap and (i - 1) / 2 operations, on any type T: Ord.
Pop: 42 is gone. Now what?
Finding the biggest is free: it's the root. Take it out, and there's a hole on top:
??
/ \
35 20
/ \ / \
30 25 15 8
/
10
Two problems. The tree has a hole, and whatever fills it has to be bigger than everything below it. What would you do?
Pop: replace, then bubble down
- Take the root. That's the answer
- Move the last value into the root's spot, so the tree stays complete
- Compare it with its children. If a child is bigger, swap with the larger child
- Repeat until both children are smaller, or there are no children
Pop from [42, 35, 20, 30, 25, 15, 8, 10]:
Step 1: take 42, move 10 up Step 2: 10 < 35 and 20, swap with 35
10 35
/ \ / \
35 20 10 20
/ \ / \ / \ / \
30 25 15 8 30 25 15 8
[10, 35, 20, 30, 25, 15, 8] [35, 10, 20, 30, 25, 15, 8]
Pop: keep going
Step 3: 10 < 30 and 25, swap with 30 Step 4: 10 has no children, stop
35 35
/ \ / \
30 20 30 20
/ \ / \ / \ / \
10 25 15 8 10 25 15 8
[35, 30, 20, 10, 25, 15, 8] [35, 30, 20, 10, 25, 15, 8]
Same bound: one row per swap, log n rows, O(log n).
What each one costs
| Operation | Cost | Why |
|---|---|---|
push(x) | O(log n) | Bubble up, one row per swap |
pop() | O(log n) | Bubble down, one row per swap |
peek() | O(1) | Read index 0 |
BinaryHeap::from(vec) | O(n) | Faster than n pushes. The appendix has why |
The reason it's log n: a complete binary tree with a million values has 20 rows. A billion, 30 rows.
Compare the sorted Vec: push costs n shifts. Here it costs at most 20 swaps.
What can be a T?
To know who's on top, the heap has to compare two values. So the type has to promise it can be compared:
use std::collections::BinaryHeap; #[derive(Debug, PartialEq, Eq)] struct Striker { name: String, goals: u32 } fn main() { let mut heap = BinaryHeap::new(); heap.push(Striker { name: String::from("Messi"), goals: 20 }); heap.push(Striker { name: String::from("Haaland"), goals: 27 }); heap.push(Striker { name: String::from("Kane"), goals: 24 }); for _ in 0..3 { let s = heap.pop().unwrap(); println!("{} ({} goals)", s.name, s.goals); } }
error[E0277]: the trait bound `Striker: Ord` is not satisfied
note: required by a bound in `BinaryHeap::<T, A>::push`
On Friday, HashSet asked for Eq + Hash. BinaryHeap asks for Ord.
The quick fix is to derive it, which takes all four comparison traits:
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Striker { name: String, goals: u32 }
That compiles, and it pops Messi first. Derived Ord compares field by field in declaration order, and name comes first. For top scorer first, we would have to write cmp ourselves.
Top K: the ten biggest of a billion
You have a billion rows and want the ten largest. Sorting all of them is O(n log n), and you'd throw away all but ten.
use std::collections::BinaryHeap; fn top_k(nums: Vec<i32>, k: usize) -> Vec<i32> { let mut heap = BinaryHeap::from(nums); // O(n) let mut result = Vec::new(); for _ in 0..k { // k times if let Some(max) = heap.pop() { // O(log n) each result.push(max); } } result } fn main() { let scores = vec![31, 7, 44, 12, 58, 23, 44, 9]; println!("{:?}", top_k(scores, 3)); // [58, 44, 44] }
Cost: O(n + k log n). For small k that's O(n), one pass over the data.
Another one, the running median of a stream of numbers, works with two heaps leaning on each other. It's in the appendix if you're curious.
Key takeaways
- A priority queue pops by priority
- A binary heap is a complete binary tree where every parent >= its children
- It's stored in a
Vec: parent at(i - 1) / 2, children at2i + 1and2i + 2 pushandpopare O(log n),peekis O(1)BinaryHeap<T>needsT: Ord, andcmpdecides what's on top
| Need | Use |
|---|---|
| Pop by priority | BinaryHeap |
| Pop the oldest first | VecDeque, on Wednesday |
| Pop the newest first | Vec |
Activity 32
See Activity 32. Problem 1 is done, so start at Problem 2.
Appendix: smallest first, with Reverse
BinaryHeap always pops the biggest. For smallest-first, wrap each value in Reverse, which flips every comparison:
use std::collections::BinaryHeap; use std::cmp::Reverse; fn main() { let mut heap = BinaryHeap::new(); heap.push(Reverse(10)); heap.push(Reverse(30)); heap.push(Reverse(20)); heap.push(Reverse(5)); println!("{:?}", heap.peek()); // Some(Reverse(5)) }
Reverse(5) is "bigger" than Reverse(10), so 5 is on top.
The ER room would actually use this: the lowest triage number is the most urgent. The running median below needs it too.
Appendix: building a heap in O(n)
BinaryHeap::from(vec) doesn't push n times. It starts from the unsorted Vec, treats it as a complete tree that happens to break the heap property, and bubbles down from the last parent back to the root.
Most nodes are near the bottom and have almost nowhere to go. Half the nodes are leaves and cost nothing. A quarter are one row up and cost at most one swap. And so on:
Total work = n/2 * 0 + n/4 * 1 + n/8 * 2 + n/16 * 3 + ...
= n * (1/4 + 2/8 + 3/16 + 4/32 + ...)
= n * 1
= O(n)
Pushing n times instead costs O(n log n), because each push can travel the full height.
Appendix: heapsort
Pop a max-heap until it's empty and the values come out in descending order. That's a sorting algorithm:
use std::collections::BinaryHeap; fn heapsort(nums: Vec<i32>) -> Vec<i32> { let mut heap = BinaryHeap::from(nums); // O(n) let mut sorted = Vec::new(); while let Some(max) = heap.pop() { // n pops, O(log n) each sorted.push(max); } sorted.reverse(); // descending to ascending, O(n) sorted } fn main() { println!("{:?}", heapsort(vec![3, 1, 4, 1, 5, 9, 2, 6])); // [1, 1, 2, 3, 4, 5, 6, 9] }
O(n) + O(n log n) + O(n) = O(n log n), the same as the sorts we've met. heap.into_sorted_vec() does the same thing.
Appendix: the running median
Numbers arrive one at a time and after each one you want the median so far. Keep two heaps: a max-heap holding the smaller half, and a min-heap holding the larger half. The median is on top of one of them, or halfway between the two tops.
use std::collections::BinaryHeap; use std::cmp::Reverse; fn main() { let mut lower = BinaryHeap::new(); // max-heap: the smaller half, biggest on top let mut upper = BinaryHeap::new(); // min-heap: the larger half, smallest on top for x in [5, 15, 1, 3, 8, 7, 9, 10] { // 1. Put it in the half it belongs to match lower.peek() { Some(&top) if x > top => upper.push(Reverse(x)), _ => lower.push(x), } // 2. Rebalance: lower has the same count as upper, or one more if lower.len() > upper.len() + 1 { let top = lower.pop().unwrap(); upper.push(Reverse(top)); } else if upper.len() > lower.len() { let Reverse(top) = upper.pop().unwrap(); lower.push(top); } // 3. The median is on top of lower, or between the two tops let median = if lower.len() > upper.len() { *lower.peek().unwrap() as f64 } else { let Reverse(hi) = *upper.peek().unwrap(); (*lower.peek().unwrap() + hi) as f64 / 2.0 }; println!("after {:>2}: median {}", x, median); } }
Each arrival is a push and maybe a pop, so O(log n) per number. Sorting after every arrival would be O(n log n) per number.
Lecture 33 - Queues: VecDeque and the ring buffer
Announcements
Learning objectives
By the end of today, you should be able to:
- Explain why popping the front of a
Vecis slow, and what a ring buffer does about it - Trace
push_backandpop_fronton a ring, including the wrap, and say where each element lives - Use
VecDequeas a queue - Choose between
Vec,VecDeque, andBinaryHeapfor a problem, and say why
Pop the oldest
Monday's table had a hole in it:
| Need | Use |
|---|---|
| Pop the newest first | Vec |
| Pop the oldest first | ? |
| Pop by priority | BinaryHeap |
Vec is slow at the front, and VecDeque is going to fix that.
Two different "stacks"
Monday we saw "heap" had two very different definitions. Today we do the same for "stack":
Stack memory:
- Where local variables live, one frame per function call
- The last function called is the first to return
Stack data structure, a way of keeping things:
pushon top,popoff the top,peekat the top- The last thing in is the first thing out
Same word because they behave the same way. The frames do form a stack. One is a region of memory, the other is a rule for a collection.
Vec is already a stack
fn main() { let mut stack: Vec<i32> = Vec::new(); stack.push(10); stack.push(20); stack.push(30); println!("{:?}", stack); // [10, 20, 30] println!("{:?}", stack.pop()); // Some(30) println!("{:?}", stack.last()); // Some(20), still there println!("{:?}", stack); // [10, 20] }
push and pop work on the end, and the end is where a Vec is cheap (because you don't need to slide anything else around).
Nothing new today on Vec.
A queue: first in, first out
A stack is LIFO (last in, first out)
A queue is FIFO (first in, first out)
Real world queues: lines at the store, printing at a shared printer, a set of downloads in the order you clicked them.
- Join at the back
- Served from the front
- The first one in is the first one out

A stack has one "editable" end. A queue has both ends: things go in at one and come out at the other.
Vec as a queue
Joining at the back is push, and that's cheap. Serving from the front:
let mut line = vec![1, 2, 3, 4, 5];
let served = line.remove(0); // 1
println!("{:?}", line); // [2, 3, 4, 5]
remove(0) gives the right answer. What does it cost?
Let's time it
100,000 jobs through a queue, one at a time:
use std::collections::VecDeque; use std::time::Instant; fn main() { let n: u64 = 100_000; let mut line: Vec<u64> = (0..n).collect(); let mut served = 0; let start = Instant::now(); while !line.is_empty() { served += line.remove(0); } println!("Vec::remove(0), {} times: {:?}", n, start.elapsed()); let mut line: VecDeque<u64> = (0..n).collect(); let start = Instant::now(); while !line.is_empty() { served += line.pop_front().unwrap(); } println!("VecDeque::pop_front, {} times: {:?}", n, start.elapsed()); println!("checksum {}", served); // so the compiler can't skip the loops }
VecDeque: a Vec with a front door
"Deque" is short for double-ended queue. We pronounce VecDeque "vec-deck."
use std::collections::VecDeque; fn main() { let mut line: VecDeque<i32> = VecDeque::new(); line.push_back(10); // join at the back line.push_back(20); line.push_back(30); println!("{:?}", line); // [10, 20, 30] println!("{:?}", line.pop_front()); // Some(10), served println!("{:?}", line.front()); // Some(20), next up line.push_front(5); // cut the line println!("{:?}", line); // [5, 20, 30] println!("{:?}", line.pop_back()); // Some(30) }
Four operations, both ends, all O(1).
How: a ring
One block, capacity 4. A head marks the front, len counts what's in it.
push_back(10), push_back(20), push_back(30)
slot: 0 1 2 3
┌─────┬─────┬─────┬─────┐
│ 10 │ 20 │ 30 │ │ head: 0 len: 3
└─────┴─────┴─────┴─────┘
▲
head
pop_front() -> Some(10)
┌─────┬─────┬─────┬─────┐
│ │ 20 │ 30 │ │ head: 1 len: 2
└─────┴─────┴─────┴─────┘
▲
head
push_back(40)
┌─────┬─────┬─────┬─────┐
│ │ 20 │ 30 │ 40 │ head: 1 len: 3
└─────┴─────┴─────┴─────┘
▲
head
push_back(50) wraps around
┌─────┬─────┬─────┬─────┐
│ 50 │ 20 │ 30 │ 40 │ head: 1 len: 4
└─────┴─────┴─────┴─────┘
▲
head
Nothing moved. The front moved, and the back wrapped around to slot 0. The block is a ring: walk off the right end and you're back at the left.
println!("{:?}", line) prints [20, 30, 40, 50], front to back, because it starts at head and walks the ring.
Activity 33, Problem 1: trace a ring
See Problem 1 on Activity 33.
Answer.
push_back x4: [ 7 | 3 | 9 | 10 ] head 0 len 4
pop_front x2: [ | | 9 | 10 ] head 2 len 2
push_back(4): [ 4 | | 9 | 10 ] head 2 len 3
push_front(8): [ 4 | 8 | 9 | 10 ] head 1 len 4
[8, 9, 10, 4], fromheadaround the ring- The front is slot 1 (the 8), because
push_frontsteppedheadback from 2 to 1. The back is slot 0 (the 4), because it wrapped
Where it lives: your Vec with one more piece of metadata
let mut line = VecDeque::with_capacity(4);
// push_back 10, 20, 30, pop_front, push_back 40, push_back 50
Stack: Heap:
┌───────────────────────────┐ ┌────┬────┬────┬────┐
│ main() │ │ 50 │ 20 │ 30 │ 40 │
│ └ line: VecDeque<i32> │ └────┴────┴────┴────┘
│ ├ ptr ─────────────────┼───▶ 0 1 2 3
│ ├ cap: 4 │
│ ├ head: 1 │
│ └ len: 4 │
└───────────────────────────┘
In Project 2 you built FastVec with ptr, len, and cap. This is that struct with one more field. Every operation is arithmetic on head:
- Element
iof the queue is at slot(head + i) % cap pop_front:head = (head + 1) % cap,len -= 1push_back: write at(head + len) % cap,len += 1
Comparing what we've seen so far:
- Hash maps used
hash % 8to find the index - Max heaps used
(i - 1) / 2 - Now we have
(head + len) % cap
What they have in common: one block in memory, and arithmetic to decide where things go.
The ring, for real
Rust won't show us head directly, but as_slices hands back the two pieces, and the first piece starts at head. Subtract the block's base pointer, and we can draw every slot:
use std::collections::VecDeque; // Print the block the way it sits in memory: every slot, in slot order, plus head fn show_raw(line: &VecDeque<i32>, base: *const i32) { let (first, second) = line.as_slices(); let head = (first.as_ptr() as usize - base as usize) / 4; // 4 bytes per i32 let mut slots: Vec<String> = vec!["__".to_string(); line.capacity()]; for (i, x) in first.iter().enumerate() { slots[head + i] = x.to_string(); } for (i, x) in second.iter().enumerate() { slots[i] = x.to_string(); } println!("[{}] head {} len {}", slots.join(" | "), head, line.len()); } fn main() { let mut line: VecDeque<i32> = VecDeque::with_capacity(4); let base = line.as_slices().0.as_ptr(); // slot 0, before anything moves line.push_back(10); line.push_back(20); line.push_back(30); show_raw(&line, base); line.pop_front(); show_raw(&line, base); line.push_back(40); show_raw(&line, base); line.push_back(50); show_raw(&line, base); println!("{:?}", line); // what Debug printing shows line.push_back(60); let base = line.as_slices().0.as_ptr(); // a new block after the doubling show_raw(&line, base); }
We had to do all this because {:?} starts at head and walks the ring, so it shows the queue in order and hides the wrap.
When it fills up
The ring was full at four. push_back(60) does what Vec does: double the block, copy everything across, free the old one. One extra step: the copy un-wraps the ring, so the queue is in one piece again and head is back at 0.
[50 | 20 | 30 | 40] head 1 len 4 cap 4, wrapped
[20 | 30 | 40 | 50 | 60 | __ | __ | __] head 0 len 5 cap 8, one piece
That's why base had to be captured again: the old block was freed, and the queue lives somewhere new.
So why not always VecDeque?
There are three costs:
- Every index is arithmetic.
v[i]is pointer plus offset.line[i]is pointer plus(head + i) % cap - The data can be in two pieces. No slice across the wrap, so no
sort()and no&line[1..3]untilmake_contiguous()copies it straight - It's the less simple thing. When you never touch the front,
Vecis smaller, simpler, and a little faster
Use VecDeque when you touch the front. Otherwise Vec.
Both ends: the last five readings
A sensor reports every second. You want the average of the last five readings, always.
use std::collections::VecDeque; fn main() { let readings = [71, 73, 70, 75, 78, 80, 77, 79]; let mut window: VecDeque<i32> = VecDeque::new(); for r in readings { window.push_back(r); // newest in at the back if window.len() > 5 { window.pop_front(); // oldest out at the front } let total: i32 = window.iter().sum(); println!("{:?} average {:.1}", window, total as f64 / window.len() as f64); } }
The window slides along the stream. Each step is one push_back and one pop_front, O(1) each, whatever the stream's length. A Vec would shift four readings every second.
We saw .iter().sum() briefly in the strings and slices lecture. After Thanksgiving we'll see what else .iter() can do.
Think-pair-share: which structure?
Vec, VecDeque, or Monday's BinaryHeap?
- The browser's back button
- A download queue: files download in the order you clicked
- Undo and redo
- A recent-files list: most recent first, never more than ten
Answer.
Vec, as a stack. Back ispopVecDeque. First clicked, first downloaded:push_back,pop_front- Two
Vecs. Undo pops the undo stack and pushes the redo stack. A new action clears redo VecDeque.push_frontthe newest, and whenlenpasses ten,pop_backthe oldest. Both ends in one structure
Summary of this week's structures
| Need | Use | Under the hood |
|---|---|---|
| Pop the newest | Vec | One block |
| Pop the oldest | VecDeque | One block, a head, % cap |
| Pop the biggest | BinaryHeap | One block, (i - 1) / 2 |
| Is this here? | HashSet | One block of buckets, hash % buckets |
| Look it up by key | HashMap | The same, with a value next to each key |
Every one of them is a Vec-shaped block on the heap plus some arithmetic. (Friday we'll see something with a different shape.)
Activity 33
See Activity 33. Problem 1 is done, so start at Problem 2.
Appendix: LinkedList
There's a third way to keep a line: each element holds a pointer to the next one, and they can sit anywhere in memory. Rust has std::collections::LinkedList, and almost nobody uses it. It makes it easy to insert between two items, but every element needs its own allocation of memory, and there's no index, so doing something like finding the tenth element means following nine pointers.
On Friday we'll build one by hand anyway, because it's the simplest structure that isn't one block, and it's our way into trees.
Appendix: make_contiguous
If you need the queue as one slice, for sort or a range, make_contiguous() copies the ring straight and hands back a &mut [T].
Lecture 34 - Trees: recursive types, from lists to game trees
Announcements
Learning objectives
By the end of today, you should be able to:
- Explain why
struct Node { next: Node }can't compile, and howOption<Box<Node>>fixes it - Draw the memory of a linked list and a tree: one block per node
- Trace search and insert on a binary search tree, and say what each costs
- Choose between Monday's
Vec-backed heap and a pointer-based tree, and defend the choice
Not a block
Recall the table we've been building:
| Need | Use | Under the hood |
|---|---|---|
| Pop the newest | Vec | One block |
| Pop the oldest | VecDeque | One block, a head, % cap |
| Pop the biggest | BinaryHeap | One block, (i - 1) / 2 |
| Is this here? | HashSet | One block of buckets, hash % buckets |
In the pre-work we asked how you'd store a family tree, where each person can have any number of children. What ideas did you have?
The max-heap trick doesn't work here
Monday's heap fit in a Vec because the tree was a complete binary tree: rows laid end to end, so a parent is at (i - 1) / 2.
But if our tree had gaps:
8 [8, 3, 10, 1, _, _, 14, _, _, _, _, _, _, 13, _]
/ \
3 10 index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
/ \
1 14
/
13
The arithmetic still works. But that's six values in fifteen slots, and every row we add doubles the block. A chain of twenty nodes would need a million slots.
Instead, each node is going to have to say where its children are.

That's a pointer! And we have one that owns what it points at: Box.
A node that points to a node
Start with one child, which makes a list. Each node holds a value and the rest of the list:
struct Node { value: i32, next: Node, // the rest of the list } fn main() {}
Box breaks the loop
A Box is always one pointer, 8 bytes, whatever is on the other end. And the list has to end somewhere, so the pointer is optional:
struct Node {
value: i32,
next: Option<Box<Node>>, // Some(pointer to the next node), or None at the end
}
Now a Node is an i32 plus one Option<Box>: 16 bytes, fixed.
The rest of the list lives on the heap, behind the pointer.
We call this structure, a list where each item points to the next, a linked list.
Where it lives: a list of three
let third = Node { value: 30, next: None };
let second = Node { value: 20, next: Some(Box::new(third)) };
let first = Node { value: 10, next: Some(Box::new(second)) };
let list: Option<Box<Node>> = Some(Box::new(first));
Stack: Heap:
┌─────────────────────────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ main() │ │ value: 10 │ │ value: 20 │ │ value: 30 │
│ └ list: Option<Box<Node>> │ │ next: Some(Box) │ │ next: Some(Box) │ │ next: None │
│ = Some(ptr) ─────────────┼──▶│ └ ptr ─────────┼──▶│ └ ptr ─────────┼──▶│ │
└─────────────────────────────┘ └──────────────────┘ └──────────────────┘ └──────────────────┘
Every Box::new is its own allocation, and the blocks can be anywhere on the heap.
The stack just holds one pointer.
Monday's BinaryHeap of a thousand numbers was one block. A list of a thousand is a thousand blocks.
The length of a list, by recursion
struct Node { value: i32, next: Option<Box<Node>>, } fn len(list: &Option<Box<Node>>) -> usize { match list { None => 0, // the end: nothing here Some(node) => 1 + len(&node.next), // this one, plus the rest } } fn main() { let third = Node { value: 30, next: None }; let second = Node { value: 20, next: Some(Box::new(third)) }; let first = Node { value: 10, next: Some(Box::new(second)) }; let list: Option<Box<Node>> = Some(Box::new(first)); println!("len {}", len(&list)); }
The type has two cases, so the function has two arms. A recursive type gets a recursive function, and the base case is None. We drew call trees like this for merge sort in the sorting lecture.
Activity 34, Problem 1: draw a list
See Problem 1 on Activity 34.
Answer.
Stack: Heap:
┌─────────────────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ main() │ │ value: 5 │ │ value: 9 │
│ └ list: Option<Box<Node>> │ │ next: Some(Box) │ │ next: None │
│ = Some(ptr) ─────────────┼──▶│ └ ptr ─────────┼──▶│ │
└─────────────────────────────┘ └──────────────────┘ └──────────────────┘
- Two blocks. A thousand nodes is a thousand blocks
2.lenis called three times: on the 5, on the 9, and on theNoneat the end
Two children: a tree
Let's give each node a second next/child node:
struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
One next made a list. Two makes a binary tree.
8
/ \
3 10 Every node is a Node with a value and two
/ \ \ Option<Box<Node>>s. A missing child is None.
1 6 14
/ \ /
4 7 13
A binary search tree
Let's add one more property we might want.
The BST property, for every node:
- Everything in the left subtree is smaller than the node
- Everything in the right subtree is bigger than the node
8 Left of 8: 3, 1, 6, 4, 7. All smaller.
/ \ Right of 8: 10, 14, 13. All bigger.
3 10
/ \ \ Left of 3: 1. Right of 3: 6, 4, 7.
1 6 14
/ \ / ...and so on, at every node.
4 7 13
It's the sorted order, hung from the middle. Read it left, node, right and you get 1, 3, 4, 6, 7, 8, 10, 13, 14.
Search: is 6 in there?
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
You want to know whether 6 is in the tree. Where do you start, and what tells you where to go next?
Search: one comparison per row
8 6 < 8: go left
/ \
3 10 6 > 3: go right
/ \ \
1 6 14 6 == 6: found it
/ \ /
4 7 13
Each comparison throws away a whole subtree. The cost is one step per row, so O(height).
For a tree that's roughly balanced, height is about . A thousand values, ten looks.
Activity 34, Problem 2: BST, heap, both, or neither?
See Problem 2 on Activity 34.
Answer.
- A: search tree only. Left of 10 is 5, 1, 7 and right is 15, 12. Not a heap: 15 is bigger than its parent
- B: max-heap only. Complete, and every parent is >= its children. Not a search tree: 40 is in the right subtree of 50, and 40 < 50
- C: both. 5 < 9 for the search tree, 9 >= 5 for the heap, and one left child keeps it complete
- D: neither. 15 > 10 breaks the heap. 12 is fine next to 5, but it's in the left subtree of 10 and 12 > 10. The search-tree rule is about every ancestor
Could C get a third node and stay both? No. A right child would have to be bigger than 9 for the search tree and at most 9 for the heap. A child under 5 breaks completeness, since row 2 isn't full.
Search, in code
fn contains(tree: &Option<Box<Node>>, target: i32) -> bool {
match tree {
None => false, // fell off the bottom
Some(node) => {
if target == node.value {
true
} else if target < node.value {
contains(&node.left, target) // check if it's on the left
} else {
contains(&node.right, target) // check if it's on the right
}
}
}
}
Same shape as len: None is the base case, Some recurses. One extra decision per node: which child.
Insert: 5 arrives. Where does it go?
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
There's exactly one spot that keeps the BST property. How do you find it?
Insert: search, then fill the hole
8 5 < 8: left
/ \
3 10 5 > 3: right
/ \ \
1 6 14 5 < 6: left
/ \ /
4 7 13 5 > 4: right. Nothing there: put it there
\
5
A new value is always a new leaf. Every insert is one Box::new, one new block on the heap, and a pointer in the parent that was None is now Some.
Cost: the same walk as search, O(height).
Where it lives: the tree
let mut tree: Option<Box<Node>> = None;
insert(&mut tree, 8);
insert(&mut tree, 3);
insert(&mut tree, 10);
Stack: Heap:
┌───────────────────────────┐ ┌──────────────────┐
│ main() │ │ value: 8 │ ┌──────────────────┐
│ └ tree: Option<Box<Node>> │ │ left: Some(Box) │ │ value: 3 │
│ = Some(ptr) ───────────┼─────▶│ └ ptr ─────────┼─────▶│ left: None │
└───────────────────────────┘ │ right: Some(Box) │ │ right: None │
│ └ ptr ─────────┼──┐ └──────────────────┘
└──────────────────┘ │ ┌──────────────────┐
└──▶│ value: 10 │
│ left: None │
│ right: None │
└──────────────────┘
Three nodes, three blocks, two pointers out of the root.
Monday's tree and today's
They're both "trees" but have different memory layouts and different jobs.
BinaryHeap (Monday) | Search tree (today) | |
|---|---|---|
| Shape | Complete, no gaps | Any shape |
| Memory | One block | One block per node |
| Find a child | Arithmetic, 2i + 1 | Follow a pointer |
| Biggest | peek, O(1) | Keep going right, O(height) |
Is x in here? | O(n), look at everything | O(height) |
| Insert | O(log n), bubble up | O(height), fill the hole |
| Everything in order | Sort it, O(n log n) | Left, node, right: O(n) |
When the tree is a list
"O(height)" is only good news when the tree is bushy.
Watch what happens if we insert 1, 2, 3, 4, 5, 6, then 7:
1
\
2
\
3 Every insert went right. Height 7.
\ Search is O(n) again: it's a linked list!
4
\
5
\
6
\
7
Real search trees rebalance themselves as they go, so height stays . Rust's BTreeMap and BTreeSet do that for you, and they're the sorted cousins of HashMap and HashSet. See the appendix.
The game tree
Project 3's minimax is a tree search too. Every position is a node, with one child for every legal move. The root is the board right now. The leaves are finished games.
[current board] X to move: take the max
/ | \
[X top] [X middle] [X bottom] O to move: take the min
/ \ / \ / \
... ... ... ... ... ... ...until the game ends
search is like len with a score instead of a count: a base case at the bottom, a recursive call per child, and the answer bubbles up.
One difference from everything else today: this tree is never stored. There's no Node and no Box. apply_move steps into a child, the recursive call explores it, and undo steps back out. The tree exists only (implicitly) in the call stack.
This week's structures
| Need | Use | Under the hood |
|---|---|---|
| Pop the newest | Vec | One block |
| Pop the oldest | VecDeque | One block, a head, % cap |
| Pop the biggest | BinaryHeap | One block, (i - 1) / 2 |
| Is this here? | HashSet | One block of buckets, hash % buckets |
| Keep it sorted while it changes | A search tree, BTreeSet | One block per node, joined by pointers |
| Look ahead in a game | A game tree | Never stored. Recursion walks it |
Key takeaways
- A type that holds itself has no size.
Option<Box<Node>>gives it one: a pointer, or nothing - One block per node. A list of a thousand is a thousand allocations, and the blocks can be anywhere
- A recursive type gets a recursive function:
Noneis the base case,Somerecurses - A binary search tree keeps left < node < right at every node. Search and insert are O(height): one comparison per row, and insert is a failed search that fills the hole
- Monday's heap is one block and arithmetic. Today's tree is pointers. Same picture, two layouts
Activity 34
See Activity 34. Problems 1 and 2 are done, so start at Problem 3.
Appendix: the search tree as a whole program
struct Node { value: i32, left: Option<Box<Node>>, right: Option<Box<Node>>, } fn contains(tree: &Option<Box<Node>>, target: i32) -> bool { match tree { None => false, Some(node) => { if target == node.value { true } else if target < node.value { contains(&node.left, target) } else { contains(&node.right, target) } } } } fn insert(tree: &mut Option<Box<Node>>, value: i32) { match tree { None => *tree = Some(Box::new(Node { value, left: None, right: None })), Some(node) => { if value < node.value { insert(&mut node.left, value) } else { insert(&mut node.right, value) } } } } fn smallest(tree: &Option<Box<Node>>) -> Option<i32> { match tree { None => None, Some(node) => match &node.left { None => Some(node.value), // nothing to the left: this is it Some(_) => smallest(&node.left), // keep going left }, } } fn main() { let mut tree: Option<Box<Node>> = None; for v in [8, 3, 10, 1, 6, 14, 4, 7, 13] { insert(&mut tree, v); } println!("{} {}", contains(&tree, 6), contains(&tree, 11)); // true false println!("{:?}", smallest(&tree)); // Some(1) }
In insert, the None arm is the only place a node is made: *tree = ... writes through the &mut and fills the hole in the parent. Equal values go to the right, so duplicates are allowed and contains still finds them. Many search trees refuse duplicates instead; BTreeSet does.
Appendix: delete, the tricky one
Search and insert only ever touch a leaf. Delete can hit a node in the middle, and there are three cases:
- No children. Set the parent's pointer to
None. The block is freed when theBoxdrops - One child. Point the parent at the child instead. The subtree under the child comes along
- Two children. Find the in-order successor, the smallest value in the right subtree (go right once, then left until you can't). Copy its value into the node, then delete the successor, which has at most one child, so it's case 1 or 2
Delete 3:
8 8
/ \ / \
3 10 4 10 4 is the smallest value to
/ \ \ -> / \ \ the right of 3, so it keeps
1 6 14 1 6 14 1 < 4 < 6, 7
/ \ / \ /
4 7 13 7 13
Still O(height). In Rust the Option<Box<Node>> juggling for case 3 is fiddly enough that it's a good exercise and a bad lecture slide.
Appendix: balance, and Rust's BTreeMap
A tree built from sorted input is a list, and every operation is O(n). Self-balancing trees fix the shape as they insert, so height stays O(log n):
- AVL trees keep the two sides of every node within one row of each other
- Red-black trees allow a little more lean for cheaper inserts
- B-trees put many values in each node, so each block holds a whole row. Databases and file systems use them, because reading one block from disk costs the same whether it holds one value or a hundred
Rust's sorted collections are B-trees: BTreeSet<T> and BTreeMap<K, V>. Same API as HashSet and HashMap, plus everything comes out in order, and you can ask for a range:
use std::collections::BTreeMap; fn main() { let mut wins = BTreeMap::new(); wins.insert("Celtics", 48); wins.insert("Bucks", 51); wins.insert("Knicks", 47); for (team, w) in &wins { // alphabetical, always println!("{}: {}", team, w); } for (team, w) in wins.range("B".."D") { // just the B's and C's println!("{}: {}", team, w); } }
The trade: HashMap is O(1) per lookup and unordered. BTreeMap is O(log n) and sorted. Pick by whether you ever need things in order.
Appendix: why not a sorted Vec?
A sorted Vec finds things by binary search in O(log n) too, and it's one block. The difference is what happens when the data changes:
| Operation | Sorted Vec | Balanced search tree |
|---|---|---|
| Search | O(log n) | O(log n) |
| Insert | O(n), shift everything after it | O(log n) |
| Delete | O(n), same | O(log n) |
| Smallest | O(1), index 0 | O(log n), keep going left |
Wednesday's remove(0) all over again. If the data is built once and searched many times, sort a Vec. If it keeps changing, use the tree.
Lecture 35 - Ship your code: modules, crates, and Python
Announcements
Learning objectives
By the end of today, I hope you will be able to (though this will not be assessed):
- Read the
mod,use, andpublines that have been at the top of your project files all term - Decide what should be
pub, and say what you're promising when you write it - Explain the difference between a package, a crate, and a module
- Say what changes when a program you run becomes a library somebody else calls
- Judge whether a piece of a Python program is worth moving to Rust, and how to hand it the data
Have you ever pip-installed Rust?
In the pre-work we asked about a Python package that turned out to be written in something else.
numpy,pandas: mostly C underneathpolars,pydantic,cryptography,tokenizers: Rust underneath
If you've typed import polars, you've run somebody else's Rust code!
Today we'll look at how they did that, and how you could too.
How does someone else get to your code?
Three sources:
- Another file in your project
- Another Rust project
- Another language
And it's the same task each time: draw a boundary, and mark what stays on one side or the other.
Let's imagine we want to share a sensor project
It has one file, src/main.rs.
It scores sensor readings: how far is each one from where it should be?
struct Reading {
id: u32,
value: f64,
baseline: f64,
}
fn load_readings(path: &str) -> Vec<Reading> { /* reads the CSV */ }
fn score_one(r: &Reading) -> f64 {
(r.value - r.baseline).abs().powf(1.5)
}
fn score_all(rs: &[Reading]) -> Vec<f64> {
rs.iter().map(score_one).collect()
}
fn mean(xs: &[f64]) -> f64 {
xs.iter().sum::<f64>() / xs.len() as f64
}
fn main() {
let rs = load_readings("sensors.csv");
println!("{}", mean(&score_all(&rs)));
}
Don't worry about the code details here - we'll cover reading them after break.
Boundary 1: another file in this project
Why split a program up at all?
Imagine Project 3 as one 900-line file. Two things can go wrong:
- It's hard to find things. The board, agents, minimax, and the tournament, all mixed up
- Everything can touch everything. Any function can call any other, so changing one can break all of them
mod addresses the first issue, and pub addresses the second.
mod makes a namespace
mod loading {
pub fn load(path: &str) -> Vec<Reading> { /* ... */ }
}
mod scoring {
pub fn score_all(rs: &[Reading]) -> Vec<f64> { /* ... */ }
}
fn main() {
let rs = loading::load("sensors.csv");
let scores = scoring::score_all(&rs);
}
A module is a named group of functions, types, and constants.
loading::load reads as "the load inside loading". Same :: as String::from.
Everything in a module starts private
mod scoring { fn adjust(x: f64) -> f64 { x.min(100.0) // cap a score at 100 } pub fn score(value: f64, baseline: f64) -> f64 { adjust((value - baseline).abs().powf(1.5)) } } fn main() { println!("{}", scoring::score(7.0, 3.0)); println!("{}", scoring::adjust(250.0)); }
You decide what to make pub
The compiler will let you write pub on everything. So the question is:
What do you want someone else to be able to reach?
Everything you mark pub is something you're promising to provide consistently and, preferably, forever.
Someone might come to depend on it, so you can't rename it or change what it returns without screwing with them.
Everything private, however, is yours to do with what you want.
Start private. Adding pub is easy, taking it away is hard.
pub works on everything
mod sensors {
pub struct Reading {
pub id: u32,
value: f64, // private field
baseline: f64, // private field
}
pub fn new(id: u32, value: f64, baseline: f64) -> Reading {
Reading { id, value, baseline }
}
}
A public struct can have private fields. Callers get a Reading and can't reach inside it, so the only way to make one is the function you gave them.
This shows up in Project 3's Board. Its cells are private, which is why you build one with Board::from_rows and change it with apply_move.
Paths say where to look
use crate::board::{Board, Cell, Position};
"Start at the top of this crate, go into board, and bring me these three names."
use super::*;
"Start at the module above this one, and bring me everything." It's the first line of every mod tests, and super is like cd ...
Moving modules into files
Once a module is big, we give it its own file.
src/
main.rs
loading.rs
scoring.rs
src/main.rs:
mod loading; // "go find src/loading.rs"
mod scoring;
fn main() {
let rs = loading::load("sensors.csv");
println!("{}", scoring::mean(&scoring::score_all(&rs)));
}
src/scoring.rs:
use crate::loading::Reading;
pub fn score_all(rs: &[Reading]) -> Vec<f64> { /* ... */ }
pub fn mean(xs: &[f64]) -> f64 { /* ... */ }
There's no mod scoring { } wrapper inside the file. The file is the module.
You've seen lines like this in your projects
The top of Project 3's minimax.rs:
use crate::agent::Agent;
use crate::board::{Board, Cell, Position};
use crate::player::Player;
And the start of its lib.rs:
pub mod agent;
pub mod board;
pub mod game;
This is what lets me define something in one file and use it in another.
Boundary 2: another Rust project
Package, crate, module
- Package: your project folder, the thing with a
Cargo.toml. Roughly, your repo - Crate: one thing that gets compiled. Roughly, your program or your library
- Module: a namespace inside a crate. Roughly, a file

Most of the time: one package, one crate, several modules.
Two kinds of crate
Binary crate. Has main(). Compiles to something you run.
sensor_tool/
Cargo.toml
src/main.rs
cargo new sensor_tool
Library crate. No main(). Compiles to something other code calls.
sensor_scoring/
Cargo.toml
src/lib.rs
cargo new --lib sensor_scoring
Every crate you've added to a Cargo.toml is the second kind.
Project 3 is one package with three crates
tictactoe/
Cargo.toml the package
src/
lib.rs library crate: the board, the agents, minimax
main.rs binary crate: cargo run
bin/arena.rs binary crate: cargo run --bin arena
Inside the library, minimax.rs says:
use crate::board::Board;
And main.rs says:
use tictactoe::board::Board;
rand, from the other side
Project 1 came with this already in it, in Cargo.toml and the random strategy:
[dependencies]
rand = "0.10"
use rand::random_range;
let guess = random_range(min..max);
Somebody wrote that lib.rs. They decided random_range was public and a lot of other things weren't. Those private things they can change without affecting anyone who uses the package.
Turning our program into a library
src/lib.rs replaces src/main.rs, and the top of the crate is now the public interface.
// src/lib.rs
mod loading;
pub mod scoring;
pub use scoring::{mean, score_all};
Two things changed, and both are small:
main()is gone. There's nothing to runpubnow decides what the outside world can reach (as opposed to whatmain.rscan use)
loading is still private.
The docs page is your pub list
cargo doc --open
That builds a website from your crate: every pub item, with its /// comments. (Try it on your project!)
docs.rs is that same page for every crate on crates.io. Here's rand's.
Installing and using public crates
Finding one: crates.io, the registry.
Adding one:
cargo add rand
which writes this into Cargo.toml for you:
[dependencies]
rand = "0.10"
Version numbers are MAJOR.MINOR.PATCH. "0.10" means "0.10.anything", so you get bug fixes without surprises. Cargo.lock records exactly what you built with.
Crates worth using
We've used: rand, clap (command-line arguments), plotters, regex
Data work: csv, serde (JSON and friends), ndarray (NumPy-shaped arrays), polars (DataFrames)
General: chrono (dates), rayon (parallelism, coming the week after break)
Before you add one, look at three things on crates.io: recent downloads, when it was last updated, and whether the docs exist.
Boundary 3: another language
Now your teammates write Python
Your team has a Python pipeline. Pandas, scikit-learn, matplotlib, everything built out.
But... one loop in it takes four minutes.
Nobody's going to rewrite that pipeline in Rust (right?)
You just want to replace the loop and leave everything else alone.
PyO3
A crate that lets Rust build something Python can import.
// src/lib.rs
use pyo3::prelude::*;
#[pymodule]
mod sensor_scoring {
use pyo3::prelude::*;
#[pyfunction]
fn score_all(values: Vec<f64>, baselines: Vec<f64>) -> Vec<f64> {
values
.iter()
.zip(baselines.iter())
.map(|(v, b)| (v - b).abs().powf(1.5))
.collect()
}
}
Look at what that is: a library crate, a mod, and two decorators.
The function inside is ordinary Rust.
#[pyfunction] acts like pub for a different audience.
Building it: maturin
pip install maturin
maturin new --bindings pyo3 sensor_scoring
You get both config files, because it's both kinds of project at once:
sensor_scoring/
Cargo.toml the Rust side
pyproject.toml the Python side
src/lib.rs your code
Write your Rust, then:
maturin develop --release
That compiles the crate and installs it into your active Python environment, the same place pip install puts things.
Same --release as cargo run --release, and it matters just as much. Without it, this module is slower than the Python it replaces.
And then it's just Python
import pandas as pd
import matplotlib.pyplot as plt
import sensor_scoring
df = pd.read_csv("sensors.csv")
scores = sensor_scoring.score_all(
df["value"].tolist(),
df["baseline"].tolist(),
)
plt.hist(scores, bins=50)
plt.show()
Loading and plotting in Python, the slow part in Rust.
Build it, import it
maturin develop --release
python
>>> import sensor_scoring
>>> sensor_scoring.score_all([7.0, 5.0], [3.0, 9.0])
[8.0, 8.0]
We ran both
A million readings, on my laptop:
| Time | |
|---|---|
| Plain Python loop | ~100 ms |
Design A: score_one, a million calls | ~115 ms |
Design B: score_all, one call | ~28 ms |
Design A moved the arithmetic into Rust and got slower.
The lesson: cross over rarely, and carry a lot with you when you do
Before you reach for Rust
NumPy does this scoring in about 8 ms:
scores = np.abs(values - baselines) ** 1.5
NumPy is the same trick, already done for you: one call, the whole column, a compiled loop underneath.
Reach for Rust when the loop can't be written as whole-column operations: each row depends on the one before it, there's real branching, or you're walking a tree.
Appendix: modules inside modules
mod pipeline { pub mod cleaning { pub fn remove_nulls() { println!("cleaned"); } } mod analysis { pub fn compute_mean() { println!("mean"); } } } fn main() { pipeline::cleaning::remove_nulls(); pipeline::analysis::compute_mean(); }
compute_mean is pub, and main still can't reach it: error[E0603]: module analysis is private. Every module on the way down has to be pub too.
An unlocked room inside a locked building is still unreachable.
Appendix: why a test can call a private function
fn half(n: i32) -> i32 { // private
n / 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_half() {
assert_eq!(half(10), 5);
}
}
mod tests is a module like any other, nested inside the file.
super is the file around it, and * is everything in there. A module can see its parent's private things, so a test can call a private helper.