簡體   English   中英

我怎樣才能得到一個Any類型的數組?

[英]How can I have an array of Any type?

我正在嘗試對類似數據框的結構建模。 我知道這里如何使用enum ,但是我正在探索如何與C#/ Python / etc類似。

我嘗試遵循Rust Trait對象轉換,但無法正常工作:

use std::any::{Any};
use std::fmt::Debug;

pub trait Value: Any + Sized {
    fn as_any(&self) -> &Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut Any {
        self
    }
}

impl Value for i32 {}

#[derive(Debug)]
struct Frame {
    data: Vec<Box<Any>>,
}

fn make_int(of: Vec<i32>) -> Frame {
    let data = of.into_iter().map(|x| Box::new(x.as_any())).collect();
    Frame {
        data: data,
    }
}

編譯器抱怨:

error[E0277]: the trait bound `std::vec::Vec<std::boxed::Box<std::any::Any>>: std::iter::FromIterator<std::boxed::Box<&std::any::Any>>` is not satisfied
  --> src/main.rs:40:61
   |
40 |     let data = of.into_iter().map(|x| Box::new(x.as_any())).collect();
   |                                                             ^^^^^^^ a collection of type `std::vec::Vec<std::boxed::Box<std::any::Any>>` cannot be built from an iterator over elements of type `std::boxed::Box<&std::any::Any>`
   |
   = help: the trait `std::iter::FromIterator<std::boxed::Box<&std::any::Any>>` is not implemented for `std::vec::Vec<std::boxed::Box<std::any::Any>>`

主要問題在於此功能:

fn as_any(&self) -> &Any {
    self
}

這意味着您可以將Value借為&Any (它將&Value轉換為&Any )。

但是然后,您想從該&Any創建Box<Any> 那將永遠無法工作,因為&Any是借來的值,而Box<Any>是擁有的。

最簡單的解決方案是更改特征以返回裝箱值(擁有的特征對象):

pub trait Value: Any + Sized {
    fn as_boxed_any(&self) -> Box<Any> {
        Box::new(self)
    }
    //The mut variation is not needed
}

現在make_int函數很簡單:

fn make_int(of: Vec<i32>) -> Frame {
    let data = of.into_iter().map(|x| x.as_boxed_any()).collect();
    Frame {
        data: data,
    }
}

更新:修補一下,我發現您可以通過編寫以下內容來創建Vec<Box<Any>>

fn make_int(of: Vec<i32>) -> Frame {
    let data = of.into_iter().map(|x| Box::new(x) as Box<Any>).collect();
    Frame {
        data: data,
    }
}

如果您僅為此轉換編寫特征,則實際上並不需要它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM