struct - 如何将特征泛型类型链接到已实现类型中的其他元素

标签 struct rust traits

我正在尝试创建一个包含通用字段的结构,该字段是基于另一个字段指定类型的。这种类型是我定义的几个结构之一。

本质上,我在这里要做的是创建一个负责设备配置的模块。这是为了处理一堆不同的设备类型。需要为所有设备配置某些规范,我创建了一个结构,在 OO 范例中,该结构将是父类(此处表示为 DeviceCfg)。然后,特定于设备类型的规范将代表子类。 (这些表示为 RaspberryPiCfg、Esp8266Cfg 等)。

我正在尝试构造事物,以便我可以引用单个对象,该对象合并了通用规范(适用于所有设备)以及特定于设备类型的规范。

use std::net::{Ipv4Addr};
use std::any::Any;


//this struct is made to show the device-type-specific configurable items
struct RaspberryPiCfg {
    led_pin : u8,
    //GPIO pin connected to the LED strip pixels (must support PWM)
    led_freq_hz : u32,
    //LED signal frequency in Hz (usually 800kHz)
    led_dma : u8,
    //DMA channel used for generating PWM signal (try 5)
    brightness : u8,
    //Brightness of LED strip between 0 and 255"
    led_invert : bool,
    //Set True if using an inverting logic level converter
    software_gamma_correction : bool
    //Set to True because Raspberry Pi doesn't use hardware dithering
    }

//this creates a default function which sets all configurable items
impl Default for RaspberryPiCfg {
    fn default() -> RaspberryPiCfg {
        RaspberryPiCfg {
            led_pin : 18,
            led_freq_hz : 800_000,
            led_dma : 5,
            brightness : 255,
            led_invert : true,
            software_gamma_correction : true
        }
    }
}
 //this struct is made to show the device-type-specific configurable items
 struct Esp8266Cfg {
    udp_ip : Ipv4Addr,
    //IP address of the ESP8266. Must match IP in ws2812_controller.ino
    udp_port : u16,
    //Port number used for socket communication between Python and ESP8266"
    software_gamma_correction : bool
    //Set to True because Raspberry Pi doesn't use hardware dithering
}


//this creates a default function which sets all configurable items
impl Default for Esp8266Cfg {
   fn default() -> Esp8266Cfg {
        Esp8266Cfg {
            udp_ip : Ipv4use std::net::{Ipv4Addr};
            udp_port : 7777,
            software_gamma_correction : false
        }
    }
}
//this struct is made to show the device-type-specific configurable items
struct BlinkstickCfg {
    software_gamma_correction : bool
    //Set to True because BlinkstickCfg doesn't use hardware dithering
}


//this creates a default function which sets all configurable items
impl Default for BlinkstickCfg {
    fn default() -> BlinkstickCfg {
        BlinkstickCfg {
            software_gamma_correction : true
        }
    }
}

enum DeviceType {
    ESP8266,
    RASPBERRY_PI,
    BLINKSTICK
}

enum StatusType {
   ERROR,
   OK
}

//this struct is made to show the configurable items that are relevant
//for all devices
struct Devicecfg {
    use_gui : bool,
    //Whether or not to display a PyQtGraph GUI plot of visualization
    display_fps : bool,
    //Whether to display the FPS when running (can reduce performance)
    pixel_num : u8,
    //Number of pixels in the LED strip (must match ESP8266 firmware)
    gamma_table_path : String,
    //Location of the gamma correction table"
    mic_rate : u32,
    //Sampling frequency of the microphone in Hz
    fps : u8,
    //Desired refresh rate of the visualization (frames per second)
    min_led_fps : u32,
    //Frequencies below this value will be removed during audio processing
    max_led_fps : u32,
    //Frequencies above this value will be removed during audio processing
    device_type : DeviceType//,
    //device_cfg : T
}

//I am trying to create a trait to implement which I could use to create
//an object which when referenced represents the configuration of 
//both a devices device-type-specific specs and the specs that are not
//specific to the type of device being configured. 
trait DeviceSpec {
    type specs;
    fn setSpecs(&self);
}

impl DeviceSpec for Devicecfg {
    fn setSpecs(&self) {
        match self.device_type {
            DeviceType::ESP8266 => {
                self.specs = Esp8266Cfg::default();
            }
            DeviceType::RASPBERRY_PI => {
                self.specs = Ra\spberryPiCfg::default();
            }
            DeviceType::BLINKSTICK => {
                self.specs = BlinkstickCfg::default();
            }
        }
    }
}

impl Default for Devicecfg {
    fn default() -> Devicecfg {
        Devicecfg {
            use_gui : true,
            display_fps : true,
            pixel_num : 65,
            gamma_table_path : "directory".to_string(),
            mic_rate : 44_100,
            fps : 60,
            min_led_fps : 200,
            max_led_fps : 12_000,
            device_type : DeviceType::ESP8266,
            device_cfg : self.setSpecificCfg();
        }
    }
}

感谢大家的帮助。我仍然是使用rust 的初学者。

最佳答案

Certain specifications will need to be configured for all devices and I have created a struct which, in an OO paradigm would be a parent class

Rust 不是一种面向对象的语言,因此应用 OO 范式不是一个好主意。也没有理由使用特征。 Rust traits 用于定义通用行为,而不是通用数据。

我认为您应该使用组合而不是继承。

enum DeviceSpecificCfg {
    RaspberryPi(RaspberryPiCfg),
    Esp8266(Esp8266Cfg),
    // ...
}

struct Devicecfg {
    // common fields ...
    device_specific_cfg: DeviceSpecificCfg
}

关于struct - 如何将特征泛型类型链接到已实现类型中的其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54453085/

相关文章:

rust - 如何将 'None' 值传递给 Rust 中的异步函数

generics - 通过其自身的通用生命周期(trait Bar <'a>: ' a)来限制特征是什么意思?

php - 覆盖 Laravel Controller 中的特征方法

C++ 初始化使用 "new"关键字分配的结构的对象成员

rust - 如何在Rust SPECS中读取组件并写入具有相同组件的新实体?

c++ - 将具有结构初始化和赋值的 C 代码移至 C++ 编译器

rust - 宏是否可以采用常量表达式和 "inline"来生成有效的 LiteralPattern?

module - 看不懂 Rust 模块系统

从另一个结构复制到新的或现有的结构

reflection - 在 Golang 结构字段中保存类型