mirror of
https://github.com/sunface/rust-by-practice.git
synced 2025-06-23 04:29:41 +00:00
add const generics
This commit is contained in:
64
solutions/generics-traits/const-generics.md
Normal file
64
solutions/generics-traits/const-generics.md
Normal file
@ -0,0 +1,64 @@
|
||||
1.
|
||||
```rust
|
||||
struct Array<T, const N: usize> {
|
||||
data : [T; N]
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let arrays = [
|
||||
Array{
|
||||
data: [1, 2, 3],
|
||||
},
|
||||
Array {
|
||||
data: [1, 2, 3],
|
||||
},
|
||||
Array {
|
||||
data: [1, 2,4]
|
||||
}
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
2.
|
||||
```rust
|
||||
fn print_array<T: std::fmt::Debug, const N: usize>(arr: [T; N]) {
|
||||
println!("{:?}", arr);
|
||||
}
|
||||
fn main() {
|
||||
let arr = [1, 2, 3];
|
||||
print_array(arr);
|
||||
|
||||
let arr = ["hello", "world"];
|
||||
print_array(arr);
|
||||
}
|
||||
```
|
||||
|
||||
3.
|
||||
```rust
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(generic_const_exprs)]
|
||||
|
||||
fn check_size<T>(val: T)
|
||||
where
|
||||
Assert<{ core::mem::size_of::<T>() < 768 }>: IsTrue,
|
||||
{
|
||||
//...
|
||||
}
|
||||
|
||||
// fix the errors in main
|
||||
fn main() {
|
||||
check_size([0u8; 767]);
|
||||
check_size([0i32; 191]);
|
||||
check_size(["hello你好"; 47]); // &str is a string reference, containing a pointer and string length in it, so it takes two word long, in x86-64, 1 word = 8 bytes
|
||||
check_size(["hello你好".to_string(); 31]); // String is a smart pointer struct, it has three fields: pointer, length and capacity, each takes 8 bytes
|
||||
check_size(['中'; 191]); // A char takes 4 bytes in Rust
|
||||
}
|
||||
|
||||
|
||||
|
||||
pub enum Assert<const CHECK: bool> {}
|
||||
|
||||
pub trait IsTrue {}
|
||||
|
||||
impl IsTrue for Assert<true> {}
|
||||
```
|
Reference in New Issue
Block a user