generics-traits/const-generics #208
Replies: 38 comments 19 replies
-
您好,练习3的题解是不是有错误,check_size无法传入String类型,因为要求String类型实现copy trait,题解中的答案会报错,需要传入String的引用好像才可以通过编译 |
Beta Was this translation helpful? Give feedback.
-
我不理解,第一题的题解有什么意义呢。(似乎并不是真正解决问题) |
Beta Was this translation helpful? Give feedback.
-
第三题报错 |
Beta Was this translation helpful? Give feedback.
-
done!请问第七题得sqrt方法要T实现什么trait? impl Point { fn main() { |
Beta Was this translation helpful? Give feedback.
-
不是很理解,第三题 pub enum Assert {} 这个枚举中,CHECK是一个const 泛型 |
Beta Was this translation helpful? Give feedback.
-
第一题怎么理解呢?直接用类型调用函数?我从c/c++语言的角度来看,不是要先定义一个变量或者参数,然后传给函数作为形参吗?那这里这样调用函数 reg_fn(S(A)) 是什么意思呢?最终是什么都没干吗?编译器怎么生成代码的这里。 |
Beta Was this translation helpful? Give feedback.
-
第三题的:我们知道 |
Beta Was this translation helpful? Give feedback.
-
🌟🌟 <T, const N: usize> 是结构体类型的一部分,和数组类型一样,这意味着长度不同会导致类型不同: Array<i32, 3> 和 Array<i32, 4> 是不同的类型 第一题:我理解的知识点是:数组每一个元素类型都要一样,如果第一个元素是[i32,3] 第二个是[i32,4] 就没法 在外面使用[]来表达 错误示范:[[i32,3],[i32,4]] |
Beta Was this translation helpful? Give feedback.
-
第三题的限制大小size是怎么算的,比如0u8对应的767?没有强类型语言经验的小白看得很懵 |
Beta Was this translation helpful? Give feedback.
-
看评论区吐槽的第三题貌似和现在看到的不一样啊,是更换题目了吗 |
Beta Was this translation helpful? Give feedback.
-
第三题描述改成取极限大小会好点吗 我做的时候直接用3个1水过去了 |
Beta Was this translation helpful? Give feedback.
-
大佬,例子中的第三个好像没法通过编译 |
Beta Was this translation helpful? Give feedback.
-
1、泛型在函数中的使用 // 填空
struct A; // 具体的类型 `A`.
struct S(A); // 具体的类型 `S`.
struct SGen<T>(T); // 泛型 `SGen`.
fn reg_fn(_s: S) {}
fn gen_spec_t(_s: SGen<A>) {}
fn gen_spec_i32(_s: SGen<i32>) {}
fn generic<T>(_s: SGen<T>) {}
fn main() {
// 使用非泛型函数
reg_fn(S(A)); // 具体的类型
gen_spec_t(SGen(A)); // 隐式地指定类型参数 `A`.
gen_spec_i32(SGen(32)); // 隐式地指定类型参数,32可以替换成任意在i32范围内的数字
// 显式地指定类型参数 `char`
generic::<char>(SGen::<char>('c'));//注意显式的写法
// 隐式地指定类型参数 `char`.
generic(SGen('c'));
} 2、泛型写一个函数 // 实现下面的泛型函数 sum
fn sum<T: std::ops::Add<Output = T>>(x:T,y:T)->T{
x+y//这里函数头需要加一个特征,不然编译器会报错,至于为什么加这个,不清楚,因为写成<T>的时候编译器给的建议是改成现在这个<T: std::ops::Add<Output = T>>
}
fn main() {
assert_eq!(5, sum(2i8, 3i8));
assert_eq!(50, sum(20, 30));
assert_eq!(2.46, sum(1.23, 1.23));
} 3、泛型写一个结构体 struct Point<T>{
x:T,
y:T,
}
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
} 4、结构体中泛型但是不同的类型 struct Point<T,S> {
x: T,
y: S,//看出来是两个不一样的泛型即可
}
fn main() {
let p = Point{x: 5, y : "hello".to_string()};
} 5、 // 为 Val 增加泛型参数,不要修改 `main` 中的代码
struct Val <T>{
val: T,
}
impl<T> Val<T> {
fn value(&self) -> &T {
&self.val
}
}
fn main() {
let x = Val{ val: 3.0 };
let y = Val{ val: "hello".to_string()};
println!("{}, {}", x.value(), y.value());
} 6、 struct Point<T, U> {
x: T,
y: U,
}
impl<T, U> Point<T, U> {
// 实现 mixup,不要修改其它代码!
fn mixup<A,B>(self,other:Point<A,B>)->Point<T,B>{//注意这边,泛型类型如何保持一致性
Point{x:self.x,y:other.y}
}
}
fn main() {
let p1 = Point { x: 5, y: 10 };
let p2 = Point { x: "Hello", y: '中'};
let p3 = p1.mixup(p2);
assert_eq!(p3.x, 5);
assert_eq!(p3.y, '中');
} 7、额,这个真是盲点了,改成泛型说是没有 结果这个标准答案和泛型不能说没有关系,只能说毫不相干🤣 struct Point<T> {
x: T,
y: T,
}
impl Point<f32> {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
fn main() {
let p = Point{x: 5.0_f32, y: 10.0_f32};//把x和y的数据类型改成f32
println!("{}",p.distance_from_origin())
} |
Beta Was this translation helpful? Give feedback.
-
Task 1. What is the target ? Where can i read about it ? |
Beta Was this translation helpful? Give feedback.
-
第7题好像不用 |
Beta Was this translation helpful? Give feedback.
-
尝试实现了一下example 3当中的 impl<T: Default + Copy, const N: usize> MinSlice<T, N> {
fn from_slice(slice: &[T]) -> Option<Self> {
if slice.len() < N {
None
} else {
let (head, _) = slice.split_at(N);
let mut res_head = [T::default(); N];
for i in 0..N {
res_head[i] = head[i]
}
Some(Self{head: res_head})
}
}
} playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e5e7b5ecba41648cc4a6535ce45ba521 |
Beta Was this translation helpful? Give feedback.
-
Rust 不支持元素类型不同的数组。 fn main() {
let arrays = [
Array {
data: [1, 2, 3],
},
Array {
data: [1.0, 2.0, 3.0],
},
Array {
data: [1, 2]
}
];
} 如果你确实需要实现类似于上述代码的效果,可以考虑 enum: #[derive(Debug)]
enum Data {
Ints(Vec<i32>),
Floats(Vec<f64>),
}
#[derive(Debug)]
struct Array {
data: Data,
}
fn main() {
let arrays = vec![
Array {
data: Data::Ints(vec![1, 2, 3]),
},
Array {
data: Data::Floats(vec![1.0, 2.0, 3.0]),
},
Array {
data: Data::Ints(vec![1, 2]),
}
];
println!("{:?}", arrays);
}
// Output: [Array { data: Ints([1, 2, 3]) }, Array { data: Floats([1.0, 2.0, 3.0]) }, Array { data: Ints([1, 2]) }] Box: use std::any::Any;
#[derive(Debug)]
struct Array {
data: Box<dyn Any>,
}
fn main() {
let arrays = vec![
Array {
data: Box::new(vec![1, 2, 3]),
},
Array {
data: Box::new(vec![1.0, 2.0, 3.0]),
},
Array {
data: Box::new(vec!["a", "b", "c"]),
}
];
println!("{:?}", arrays);
}
// Output: [Array { data: Any { .. } }, Array { data: Any { .. } }, Array { data: Any { .. } }] |
Beta Was this translation helpful? Give feedback.
-
第六题为什么self参数不用&self |
Beta Was this translation helpful? Give feedback.
-
请教下 Assert<{ core::mem::size_of::() < 768 }>: IsTrue, |
Beta Was this translation helpful? Give feedback.
-
最后一题个人理解:
|
Beta Was this translation helpful? Give feedback.
-
《Const 泛型》这一节练习题的第三个例子似乎过不了编译: pub struct MinSlice<T, const N: usize> {
pub head: [T; N],
pub tail: [T],
}
fn main() {
let slice: &[u8] = b"Hello, world";
let reference: Option<&u8> = slice.get(6);
// 我们知道 `.get` 返回的是 `Some(b' ')`
// 但编译器不知道
assert!(reference.is_some());
let slice: &[u8] = b"Hello, world";
// 当编译构建 MinSlice 时会进行长度检查,也就是在编译期我们就知道它的长度是 12
// 在运行期,一旦 `unwrap` 成功,在 `MinSlice` 的作用域内,就再无需任何检查
let minslice = MinSlice::<u8, 12>::from_slice(slice).unwrap();
let value: u8 = minslice.head[6];
assert_eq!(value, b' ')
} 尝试 error[E0599]: no function or associated item named `from_slice` found for struct `MinSlice` in the current scope
--> src/main.rs:17:40
|
1 | pub struct MinSlice<T, const N: usize> {
| -------------------------------------- function or associated item `from_slice` not found for this struct
...
17 | let minslice = MinSlice::<u8, 12>::from_slice(slice).unwrap();
| ^^^^^^^^^^ function or associated item not found in `MinSlice<u8, 12>`
For more information about this error, try `rustc --explain E0599`.
error: could not compile `b` (bin "b") due to 1 previous error
[Process exited 101] |
Beta Was this translation helpful? Give feedback.
-
generics-traits/const-generics
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/generics-traits/const-generics.html
Beta Was this translation helpful? Give feedback.
All reactions