以下Rust代码无法编译:
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Self::Bar
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息让我困惑:
error[E0599]: no associated item named `Bar` found for type `Foo` in the current scope
--> src/main.rs:7:9
|
7 | Self::Bar
| ^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这个问题可以通过使用Foo而不是来解决Self,但这让我觉得奇怪,因为Self它应该引用正在实现的类型(忽略特征),在这种情况下是Foo.
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Foo::Bar
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不能Self在这种情况下使用?哪里可以Self使用*?还有什么我可以用来避免在方法体中重复类型名称吗?
*我忽略了traits中的用法,其中Self指的是实现特征的任何类型.
以下代码无法编译:
use std::str::Chars;
struct Chunks {
remaining: Chars,
}
impl Chunks {
fn new(s: String) -> Self {
Chunks {
remaining: s.chars(),
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:
use std::str::Chars;
struct Chunks {
remaining: Chars,
}
impl Chunks {
fn new(s: String) -> Self {
Chunks {
remaining: s.chars(),
}
}
}
Run Code Online (Sandbox Code Playgroud)
Chars不拥有要迭代的字符,也不能超过其&str或String从其创建的字符。
是否存在Chars不需要生存期参数的私有版本,或者我必须自己保留Vec<char>和索引?
我有Iterator<Item = &(T, U)>一片&[(T, U)]。我想将此迭代器解压缩到其组件中(即获取(Vec<&T>, Vec<&U>))。
Rust 通过以下.unzip()方法提供解压缩功能Interator:
points.iter().unzip()
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不能按原样工作,因为.unzip()期望迭代器项的类型是元组;我的是对元组的引用。
为了解决这个问题,我尝试编写一个函数,该函数在对元组的引用和引用元组之间进行转换:
fn distribute_ref<'a, T, U>(x: &'a (T, U)) -> (&'a T, &'a U) {
(&x.0, &x.1)
}
Run Code Online (Sandbox Code Playgroud)
然后我可以map通过结果迭代器来获得.unzip()可以处理的东西:
points.iter().map(distribute_ref).unzip()
Run Code Online (Sandbox Code Playgroud)
这现在有效,但我觉得有点奇怪。特别是,它distribute_ref似乎是 Rust 标准库提供的一个相当简单的操作。我猜它要么是,我找不到它,要么我没有以正确的方式接近这个。
有一个更好的方法吗?
在下面的示例中,模块outer具有私有类型Private和私有内部模块inner.inner能够访问Private(因为子模块可以访问其父项的私有项,即使它们没有被公开).
inner定义一个函数not_really_public_interface().虽然它被标记为公开,但它实际上只能用于outer因为inner它本身不公开.
outer.rs
struct Private;
mod inner {
use super::Private;
pub fn not_really_public_interface() -> Private {
Private
}
}
Run Code Online (Sandbox Code Playgroud)
这编译没有任何问题.
outer应该能够用来inner::not_really_public_interface()获取Private,只要它确保不输出它.所以我们这样做:
pub fn main() {
let _ = self::inner::not_really_public_interface();
}
Run Code Online (Sandbox Code Playgroud)
对?
标准错误
error[E0446]: private type `Private` in public interface
--> src/outer.rs:4:3
|
4 | / pub fn not_really_public_interface() -> Private {
5 | | Private …Run Code Online (Sandbox Code Playgroud)