简体   繁体   中英

Rust meta / compound structs with marker traits

I have multiple existing structs that I want to share between code contexts using a pubsub mechanism with shared "topics" (where each topic publishes a single type). Many topics reuse the same struct types, so I'd like to somehow mark the original structs to reuse them for those topics. Something like:

trait TopicMeta {
    const TOPIC: &'static str;
}

struct Point {
    x: u32,
    y: u32,
}

impl TopicMeta for Point as HomeLocation  {
    const TOPIC: &'static str = "home";
}

impl TopicMeta for Point as RoverLocation  {
    const TOPIC: &'static str = "rover";
}

However, as far as I can tell there's no way to do this?

Other options:

  • I could create a new type for each topic, identical to the original Point struct except for its name.
  • I could create a wrapper object for each topic with an inner field that contains the Point.

Any suggestions?

A common way to do this is to add a field to your type and use unit struct as tags:

trait TopicMeta {
    const TOPIC: &'static str;
}

struct Point<T> {
    x: u32,
    y: u32,
    tag: T,
}

struct HomeLocation;
struct RoverLocation;

impl TopicMeta for Point<HomeLocation> {
    const TOPIC: &'static str = "home";
}

impl TopicMeta for Point<RoverLocation> {
    const TOPIC: &'static str = "rover";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM