Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions 1_concepts/1_9_phantom/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ name = "step_1_9"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
rand = "0.8"
32 changes: 31 additions & 1 deletion 1_concepts/1_9_phantom/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,33 @@
use std::marker::PhantomData;
use rand;

trait HasFacts {
const FACTS: &'static [&'static str];
}

impl<T> HasFacts for Vec<T> {
const FACTS: &'static [&'static str] = &[
"Vec is heap-allocated.",
"Vec may re-allocate on growing.",
];
}

struct Fact<T>(PhantomData<T>);

impl<T: HasFacts> Fact<T> {
fn new() -> Self {
Fact(PhantomData)
}

fn fact(&self) -> &str {
let facts = T::FACTS;
let idx = rand::random::<usize>() % facts.len();
facts[idx]
}
}

fn main() {
println!("Implement me!");
let f: Fact<Vec<i32>> = Fact::new();
println!("Fact about Vec: {}", f.fact());
println!("Fact about Vec: {}", f.fact());
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Each step must be performed as a separate [PR (pull request)][PR] with an approp
- [ ] [1.6. Static and dynamic dispatch][Step 1.6] (1 day)
- [ ] [1.7. `Sized` and `?Sized` types][Step 1.7] (1 day)
- [ ] [1.8. Thread safety][Step 1.8] (1 day)
- [ ] [1.9. Phantom types][Step 1.9] (1 day)
- [x] [1.9. Phantom types][Step 1.9] (1 day)
- [ ] [2. Idioms][Step 2] (2 days, after all sub-steps)
- [ ] [2.1. Rich types ensure correctness][Step 2.1] (1 day)
- [ ] [2.2. Swapping values with `mem::replace`][Step 2.2] (1 day)
Expand Down