走进 Rust;高级 trait
Rust 大约 969 字关联类型 associated types
将类型占位符与trait
相关联的方式,这样trait
的方法签名中就可以使用这些占位符类型。
trait
的实现者会针对特定的实现在这个占位符类型指定相应的具体类型。
标准库中的 Iterator
Item
是一个占位符类型。
next
方法返回的Option<Self::Item>
类型。
Iterator
的实现者会指定Item
的具体类型
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
标准库中的 Iterator 实现
Chars
实现了Iterator
,指定了Item
占位符类型是char
。
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Iterator for Chars<'a> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
// SAFETY: `str` invariant says `self.iter` is a valid UTF-8 string and
// the resulting `ch` is a valid Unicode Scalar Value.
unsafe { next_code_point(&mut self.iter).map(|ch| char::from_u32_unchecked(ch)) }
}
}
自定义实现 Iterator
Counter
是自定义的结构体,实现Iterator
,指定Item
为u32
类型。
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
// --snip--
}
}
阅读 347 · 发布于 2023-04-11
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓
昵称:
随便看看
换一批
-
PostgreSQL 判断字符串是否以指定文字开头阅读 432
-
Java 中的 InheritableThreadLocal阅读 2141
-
走进 Rust:结构体阅读 2635
-
Go JSON Tag阅读 3689
-
Java 消除 if else 代码的几种方式阅读 2960
-
MySQL 备份工具 xtrabackup 安装和使用阅读 2115
-
Android MediaMetadataRetriever 获取多媒体文件信息阅读 4456
-
macOS OpenSSL 生成 p12 证书阅读 123
-
IDEA Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:2.5阅读 2438
-
Android 监听 SIM 卡状态阅读 5978