-
Notifications
You must be signed in to change notification settings - Fork 0
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
apocrypha-rs #13
Comments
§1.4 仅仅是 Hello world在 §1.4 不仅是 Hello world 一节,该教程给出了如下代码: fn greet_world() {
let southern_germany = "Grüß Gott!";
let chinese = "世界,你好";
let english = "World, hello";
let regions = [southern_germany, chinese, english];
for region in regions.iter() {
println!("{}", ®ion);
}
}
fn main() {
greet_world();
}
Rust 一系列用于格式化的宏非常类似, 考察 无论是这里占位符处变量的类型,还是
Rust 的集合类型确实不能直接进行循环,但数组(array)不算是 Rust 的集合类型,而是基本类型(primitive),好比 C++ 的 但数组的情况很特殊。在返回值的 for i in [1, 2, 3] .iter() { /* i: &i32; */ } // 1
for i in [1, 2, 3] { /* i: i32; */ } // 2
for i in (&[1, 2, 3]).iter() { /* i: &i32; */ } // 3
for i in &[1, 2, 3] { /* i: &i32; */ } // 4
// ~> coercion
// => call
// -> type
//
// 1: [i32; 3] ~> [i32] => .iter() -> slice::Iter[i32] => .into_iter() -> slice::Iter[i32]
// 2: [i32; 3] => .into_iter() -> array::IntoIter<i32, 3>
// 3: &[i32; 3] ~> [i32] => .iter() -> slice::Iter[i32] => .into_iter() -> slice::Iter[i32]
// 4: &[i32; 3] => .into_iter() -> slice::Iter[i32] |
§2.6.1 Not matching when
|
§2.8.1 Not-so-generic generics参看《§2.8.1 泛型》一节。
这段代码的错误一眼没看出来……不止需要按下文所说增加 且慢,比较两个变量只需要读取它们的值,并不会修改它。回想 bool operator< (const X& lhs, const X& rhs) 还有 Rust 的 pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs>
where
Rhs: ?Sized,
{
fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
...
} 分别用的常量引用和只读引用。既然用引用就好了,那么为什么还要 fn largest<T: PartialOrd>(list: &[T]) -> &T { // 生命周期擦除
let mut largest = &list[0];
for item in list.iter() { // 这里不需要写 &,item 本身是 &T
if item > largest {
largest = item;
}
}
largest
} 且慢,根据你的离散数学知识,你要在一些具有 当然,更 Rust 的写法不应该这么过程式: #[inline]
fn largest<T: Ord>(list: &[T]) -> &T {
list.iter().max().unwrap()
} 为什么需要 更新:原来在《§2.8.2 特征》一节讲了这个 |
§2.8.2 Coping with copy and
|
§2.8.4 You only implement once《§2.8.4 深入了解特征》中提到了关联类型:
参考 The Book,关联类型(associated types)最重要的作用实际上是避免多态。如果使用 impl Iterator<String> for MyIterator<String> {} // OK
impl Iterator<i32> for MyIterator<String> {} // ??? 允许产生除了 也就是说,泛型特征是一个类型在实现这个特征时,针对不同的类型可以有不同的实现(比如同样是吃东西,吃炒菜用筷子,但吃蛋糕用叉子),而关联类型则是不同的类型实现这个特征时可能关联到不同的类型,但特定类型实现这个特征时,关联到的类型是唯一的(比如餐厅都是可以吃饭的,不同餐厅可能提供不同的菜式,但在中餐厅只能吃到中餐,在西餐厅只能吃到西餐)。 |
title: Rust 语言伪经
date: 2022-08-04
category: comp
genre: note
tags:
keywords:
某汉语 Rust 教程没能正确告诉你的内容。
从个人喜好来说,我不喜欢某 Rust 中文教程。不可否认的是,它诸如索引的一些设计还是较为科学的,但我不太喜欢它的行文风格,过于泛滥的幽默之笔对于我来说似乎更容易发散掉注意力。我个人偏好官方出品的原版教材,The Book,它的行文比较紧凑且知识密集,当然可能略显枯燥。
客观来说,官方出品的教程在内容的准确性上更值得信赖。笔者本身对 Rust 的了解极其浅显,但对该中文教程中的一部分内容存有一些疑问。本篇的目标是,尽可能客观地考证并指出该中文教程中的偏误。
The text was updated successfully, but these errors were encountered: