【问题标题】:Is there a safe way to reuse the same code for immutable and mutable variants of a function? [duplicate]是否有一种安全的方法可以为函数的不可变和可变变体重用相同的代码? [复制]
【发布时间】:2019-06-25 21:22:26
【问题描述】:

我搜索了一下,找到了this Reddit post from four years ago,但除了不安全的代码:

fn find_mut <'a> (&'a mut self, elem: &T) -> Option<&'a mut Node<T>> {
    unsafe{std::mem::transmute(self.find(elem))}
}   

或宏,我想不出任何方法来做到这一点。

问题的替代重述:

  • 使函数泛型而不是可变性。
  • 可变性修饰符多态性。

现在有办法吗?


动机,以防万一这是另一个 XY 问题:我想编写一个函数来处理引用向量,读取它们但不修改它们,并且我想在我将使用这些函数的情况下有&amp;Ts 和&amp;mut Ts。

【问题讨论】:

  • 请注意,将不可变引用转换为可变引用总是不安全,don't do it ever

标签: generics reference rust immutability mutability


【解决方案1】:

根据您在邮件末尾描述的动机,我的理解是您希望使用一个函数检查 Vec&lt;&amp;T&gt;Vec&lt;&amp;mut T&gt;,而不修改底层 Ts。这是做你想做的吗?请注意,我使用了对切片的引用,因为它作为参数比对向量的引用更惯用,因为后者强制前者。

Playground

use std::ops::Deref;

struct Foo;

fn do_stuff(_: &Foo) {}

fn process<T>(v: &[T])
where
    T: Deref<Target = Foo>,
{
    for x in v.iter().map(|x| x.deref()) {
        do_stuff(x);
    }
}

fn main() {
    process(&[&Foo]);
    process(&[&mut Foo]);
}

使用Borrow代替Deref,也可以通过&amp;[Foo]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-10
    • 2022-11-17
    • 2011-11-10
    • 2020-11-05
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多