Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update const-generics.md #457

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 17 additions & 3 deletions en/src/generics-traits/const-generics.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,25 @@ fn main() {}
3. Const generics can also let us avoid some runtime checks.
```rust
/// A region of memory containing at least `N` `T`s.
pub struct MinSlice<T, const N: usize> {
pub struct MinSlice<'a, T, const N: usize> {
/// The bounded region of memory. Exactly `N` `T`s.
pub head: [T; N],
/// Zero or more remaining `T`s after the `N` in the bounded region.
pub tail: [T],
pub tail: &'a [T],
}
impl<'a, T: std::marker::Copy + std::default::Default, const N: usize> MinSlice<'a,T,N> {
fn from_slice(slice: &'a [T]) -> Option<Self> {
if slice.len() >= N {
let mut head = [T::default(); N];
let (head_slice, tail) = slice.split_at(N);
for (dst, src) in head.iter_mut().zip(head_slice.iter()) {
*dst = *src;
}
Some(Self { head, tail })
} else {
None
}
}
}

fn main() {
Expand Down Expand Up @@ -142,4 +156,4 @@ pub trait IsTrue {}
impl IsTrue for Assert<true> {}
```

> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/const-generics.md)(under the solutions path), but only use it when you need it :)
> You can find the solutions [here](https://github.com/sunface/rust-by-practice/blob/master/solutions/generics-traits/const-generics.md)(under the solutions path), but only use it when you need it :)