如何为`&'static str: From<&'a T>`定义 trait bound?
如何为
&'static str: From<&'a T>定义 trait bound? 我猜你应该是想让你的枚举和内部类型都能顺畅转成&'static str,同时给 trait 加上精准的约束对吧?先看看你给出的原实现代码:
pub trait InnerTypeTrait: Debug + Clone + std::fmt::Display + PartialEq + Eq + Into<&'static str> + Send + Sync + 'static { } #[derive(Debug, Clone, strum::Display, PartialEq, Eq, strum::IntoStaticStr)] pub enum OuterType<R: InnerTypeTrait> { Foo #[strum(transparent)] Bar(R), }
你这里给InnerTypeTrait加了Into<&'static str>的约束,但结合Strum的IntoStaticStr宏来看,可能需要调整约束方式来适配透明变体的需求,或者更精准地表达生命周期相关的转换逻辑。下面给你两个可行的调整方案:
方案一:直接用
From的泛型生命周期约束
如果你想明确表达「不管R的引用生命周期是啥,都能转成&'static str」,可以把for<'a> From<&'a Self>作为 trait bound,或者写在trait的where从句里,这样的约束更贴合「从任意生命周期的引用转静态字符串」的需求:use std::fmt::Debug; use strum::{Display, IntoStaticStr}; // 方式1:直接加到trait的继承列表中 pub trait InnerTypeTrait: Debug + Clone + std::fmt::Display + PartialEq + Eq + for<'a> From<&'a Self> + Send + Sync + 'static { } // 方式2:用where从句更清晰地展示约束逻辑 pub trait InnerTypeTrait: Debug + Clone + std::fmt::Display + PartialEq + Eq + Send + Sync + 'static where &'static str: for<'a> From<&'a Self>, { }方案二:结合Strum宏的原生约束
因为你给Bar(R)加了#[strum(transparent)],Strum会要求R本身也能生成对应的静态字符串。所以直接把strum::IntoStaticStr加到InnerTypeTrait的约束里,会更适配Strum的宏生成逻辑,不用自己手动处理字符串转换的细节:use std::fmt::Debug; use strum::{Display, IntoStaticStr}; pub trait InnerTypeTrait: Debug + Clone + std::fmt::Display + PartialEq + Eq + IntoStaticStr + Send + Sync + 'static { } #[derive(Debug, Clone, Display, PartialEq, Eq, IntoStaticStr)] pub enum OuterType<R: InnerTypeTrait> { Foo, #[strum(transparent)] Bar(R), }
这两种方案都能让你的OuterType正常通过Strum生成静态字符串转换的实现,同时InnerTypeTrait的约束也能准确匹配你的需求。
内容来源于stack exchange
相关产品推荐
相关产品推荐

