小编GGa*_*zzi的帖子

我可以用特征对象键入内省然后向下转换吗?

我有一个集合Trait,一个迭代它并执行某些操作的函数,然后我想检查实现者类型,如果它是类型Foo然后向下转换它并调用一些Foo方法.

基本上,类似于Go的类型切换界面转换.

搜索我发现任何特征,但它只能在'static类型上实现.

为了帮助展示我想要的东西:

let vec: Vec<Box<Trait>> = //

for e in vec.iter() {
    e.trait_method();

    // if typeof e == Foo {
    // let f = e as Foo;
    // f.foo_method();
    //}
}
Run Code Online (Sandbox Code Playgroud)

rust

10
推荐指数
1
解决办法
2303
查看次数

我有什么方法可以使用方法中的self作为Rc <RefCell <T >>?

我有一个具有Rc<RefCell<Bar>>字段的结构(Foo),Bar有一个被a调用的方法Rc<RefCell<Bar>>,在该方法中它获取对Foo的引用,我想Rc<RefCell<Bar>>在那个Foo 中将其设置为调用该方法的Bar .

请考虑以下代码:

struct Foo {
    thing: Rc<RefCell<Bar>>,
}

struct Bar;

impl Foo {
    pub fn set_thing(&mut self, thing: Rc<RefCell<Bar>>) {
       self.thing = thing;
    }
}

impl Bar {
    pub fn something(&mut self) {
        // Things happen, I get a &mut to a Foo, and here I would like to use this Bar reference
        // as the argument needed in Foo::set_thing            
    }
}

// Somewhere else
// Bar::something is called from something like …
Run Code Online (Sandbox Code Playgroud)

rust

8
推荐指数
1
解决办法
836
查看次数

impl convert :: From for(mutable)reference

我正在尝试实现From一个我想要作为一个可变参考的类型,所以我把它推到一个&mut TheType,但那我该怎么称呼from?我尝试执行的尝试失败,因为它尝试做反射(TheType from TheType)或不能(或不知道如何)from从类型调用&mut TheType.

代码将更好地解释它:

enum Component {
    Position(Point),
    //other stuff
}

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

impl<'a> std::convert::From<&'a mut Component> for &'a mut Point {
    fn from(comp: &'a mut Component) -> &mut Point {
        // If let or match for Components that can contain Points
        if let &mut Component::Position(ref mut point) = comp {
            point
        } else { panic!("Cannot make a Point out of this …
Run Code Online (Sandbox Code Playgroud)

traits rust

2
推荐指数
1
解决办法
113
查看次数

将函数(动态分配)与特定参数一起分配给变量.

好的,所以这是交易,比如我有一个函数(take_action),它调用另一个函数.但我们不知道take_action将调用哪个函数.

由于这个问题我得知这一部分,问题是,在那个问题上他们处理的是不带参数的函数,我的take_action可以采用几个不同的函数之一,彼此完全不同,采取完全不同的行为,不同的论点.

现在来看一些示例代码:

def take_action():
    action['action']()
    #does other stuff with 'other_stuff_in_the_dic'

def move(x,y):
    #stuff happens

action = {'action': move, 'other_stuff_in_the_dic': 'stuff' }
Run Code Online (Sandbox Code Playgroud)

(在这种情况下,'动作'会移动,但就像我说的那样,根据某些用户输入动态分配)

我想做的是这样的:

action = { 'action': move(2,3), 'other_stuff': 'stuff' }
Run Code Online (Sandbox Code Playgroud)

(显然在那里调用函数,因为它有(),因此它不起作用)

我只是一个初学程序员,我唯一想到的是使用一个列表,它位于dic中的另一个键中,但是它只传递一个列表参数,而不是传递列表的每个内容作为论点.

实现这一点的方法是什么,所以'action'键(或另一个键上的字典?)还存储了我在take_action上调用它时应该使用的参数?

python

0
推荐指数
1
解决办法
77
查看次数

标签 统计

rust ×3

python ×1

traits ×1