【发布时间】:2020-06-10 12:40:11
【问题描述】:
我有以下代码:
use std::convert::{From, Into};
#[derive(PartialEq, Debug)]
enum FindBy<'f> {
U(&'f usize),
S(&'f str),
ST(&'f String),
}
impl<'f> From<&'f usize> for FindBy<'f> {
fn from(v: &'f usize) -> Self {
Self::U(v)
}
}
impl<'f> From<&'f str> for FindBy<'f> {
fn from(v: &'f str) -> Self {
Self::S(v)
}
}
impl TileSet {
pub fn find<'r, 'ts: 'r, K: Into<FindBy<'r>>>(&'ts self, key: K) -> &'r Tile {
match key.into() {
FindBy::S(k) => &self.list.get(k).unwrap(),
FindBy::ST(k) => &self.list.get(k).unwrap(),
FindBy::U(k) => match &self.list.get_index(*k) {
Some((_, v)) => &v,
_ => todo!(),
},
}
}
}
导致此警告:
warning: private type `prelude::sys::element::tile_set::FindBy<'r>` in public interface (error E0446)
--> src/sys/element/tile_set.rs:46:5
|
46 | / pub fn find<'r, 'ts: 'r, K: Into<FindBy<'r>>>(&'ts self, key: K) -> &'r Tile {
47 | | match key.into() {
48 | | FindBy::S(k) => &self.list.get(k).unwrap(),
49 | | FindBy::ST(k) => &self.list.get(k).unwrap(),
... |
54 | | }
55 | | }
| |_____^
|
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #34537 <https://github.com/rust-lang/rust/issues/34537>
FindBy 从未公开——它的目的是提供一个白名单以允许一个参数采用多种类型,但该类型本身绝不打算在外部使用,仅供内部使用,但它抱怨私有类型在公共界面中。
请允许我澄清一下,FindBy 永远不会在它所在的模块/文件之外使用,但它是函数签名的一部分,函数是 public。
我不想公开 FindBy,但它从来没有公开,但因为它在公共函数中用于为参数提供类型白名单,所以 Rust 抱怨。
解决这个问题的最佳方法是什么?
【问题讨论】:
-
很难回答您的问题,因为它不包含minimal reproducible example。您提供的代码不会产生您所询问的错误。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!
-
您的问题似乎可以通过How to reference private types from public functions in private modules? 或Private inner module returning private item gives “private type in public interface” error 的答案得到解答。如果没有,请edit您的问题来解释差异。否则,我们可以将此问题标记为已回答。
-
这些问题似乎是关于返回私有类型,这不是我要问的,因为我没有返回私有类型;正如我所说的“但类型本身绝不打算在外部使用,仅供内部使用”。
-
"returning" vs "accepting" 在这里不相关,关键是类型在签名中。您是否尝试解决方案以查看它们是否有效?