默认实现 self 类型的 Rust 特征方法不是预期的

问题描述 投票:0回答:1

所以我有这个

FileSystem
铁锈的特征

pub trait FileSystem: Debug + Send + Sync

在这个特征中,我这里有一个带有默认实现的方法:

fn location_with_sub_path(&self, sub_path: &[&str]) -> FileSystemLocation {
    FileSystemLocation::new(
        Arc::new(self.clone()),
        sub_path
            .into_iter()
            .map(|sub_path_component| sub_path_component.to_string())
            .collect()
    )
}

但是正如你在这里看到的,这个方法给出了一个错误

该错误表明

self
类型未实现
FileSystem
FileSystemLocation
的构造函数采用
Arc<dyn FileSystem>
,换句话说,是一个包含任何在其中实现
FileSystem
的对象的弧。

pub fn new(file_system: Arc<dyn FileSystem>, sub_path: Vec<String>) -> Self {
    Self {
        file_system,
        sub_path,
    }
}

但是考虑到我对

FileSystem
特征的默认实现是出于明显的原因,仅存在于实现
FileSystem
的数据类型上,我不确定为什么 rust 不能假设这一点并像往常一样编译代码。

我已经认识到,几乎所有时候,rust 编译器都是正确的,但显然我遗漏了一些东西,因为我不确定为什么它不能编译。

rust struct polymorphism traits type-inference
1个回答
0
投票

我认为错误消息可能有点误导 - 几乎可以肯定您想要一个

Arc<Self>
而不是
Arc<&Self>
?当传递
&self
时,如果
clone
上不存在
Self
,则
self.clone()
只是通过其
Copy
实现克隆引用。您可能想要的是将
arc_self: Arc<Self>
作为第一个参数传递给
location_with_sub_path
,然后传递
Arc::clone(&arc_self)
,或者传递
self
而不是
&self
,并确保它可以被克隆。

© www.soinside.com 2019 - 2024. All rights reserved.