Advanced Topic 46 of 50 Languages & Compilers
Linear and Affine Types
Types restricting how many times a value is used.
How it works
Linear types require that every value be used exactly once, and affine types allow at most once, so a value can be dropped but not duplicated. This tracks resources through a program: after a value is consumed or moved, it cannot be used again, making it possible to enforce protocols and manage memory, file handles and locks statically. Rust's ownership is based on affine types, and Haskell's LinearTypes extension, Idris 2 and Clean explore linearity.
Step-by-step walkthrough
- A linear value must be used exactly once.
- Using it consumes it.
- A second use is a compile-time error.
- Affine types allow at most one use, which is Rust's moves.
- They model files, locks and memory safely.
Where it is used
Preventing use-after-close of files, safe in-place updates of data structures, session types for communication protocols and memory safety without garbage collection use linear and affine types.
Common pitfall
Code must thread resources through functions explicitly, which can be awkward, and borrowing mechanisms are needed to make them practical. Copyable values need to be distinguished from non-copyable ones. Error messages about moved values confuse newcomers. Understand the difference between must-use and may-drop semantics.
Where it fits in the course
Linear and Affine Types is topic 46 of 50 in Languages & Compilers, rated Advanced. It follows Dependent Types. The next topic is Garbage Collection Algorithms.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Languages & Compilers quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Languages & Compilers quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Linear and Affine Types?
Where do people use Linear and Affine Types?
What is the most common mistake with Linear and Affine Types?
What should I learn before this topic?
How can I practice it?
Is Linear and Affine Types hard to learn?
How long does it take to learn Linear and Affine Types?
Which topics are related to Linear and Affine Types?
What should I study after Linear and Affine Types?
Related topics
- Dependent Types (Languages & Compilers)
- Garbage Collection Algorithms (Languages & Compilers)
- Hindley-Milner Inference (Languages & Compilers)
- Domain-Specific Languages (Languages & Compilers)
- Data Types (Programming Fundamentals)
- Linear Search (Algorithms)
- Malware Types (Security & Cryptography)