是否可以将可变引用的值中的变体更改为枚举? [英] Is it possible to switch variants in the value of a mutable reference to an enum?

查看:115
本文介绍了是否可以将可变引用的值中的变体更改为枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 T <?c 之间的附加限制下切换可变引用的值(& mut E / code>,而不诉诸不安全的代码?



这就是给定枚举:

 枚举E< T> {
VariantA(T),
VariantB(T)
}

正确的写法方式是什么?

  let x:E< ??? = E :: VariantA(??); 
change_to_variant_b(& mut x);
assert_eq!(x,E :: VariantB(??));


解决方案

我将在这里度过一个肢体






可能只是轻微更改了签名: (e:E T) - > E< T> {
match e {
E :: VariantA(t)=> E :: VariantB(t),
E :: VariantB(t)=> E :: VariantB(t),
}
}






可以使用不安全

  fn change_to_variant_b< T>(e:& mut E T){
use std :: ptr;

unsafe {
match ptr :: read(e as * const _){
E :: VariantA(t)=> ptr :: write(e as * mut _,E :: VariantB(t)),
E :: VariantB(t)=> ptr :: write(e as * mut _,E :: VariantB(t)),
}
}
}






可以附加边界(默认克隆):

  fn change_to_variant_b< T:Default>(e:& mut E T){
match std :: mem :: replace(e,E :: VariantA(T :: default())){
E :: VariantA(t)=> e = E :: VariantB(t),
E :: VariantB(t)=> e = E :: VariantB(t),
}
}


Is it possible to switch variants in the value of a mutable reference (&mut E<T>) without additional constraints on T, and without resorting to unsafe code?

That is, given an enum:

enum E<T> {
    VariantA(T),
    VariantB(T)
}

What is the correct way of writing this:

let x: E<???> = E::VariantA(??);
change_to_variant_b(&mut x);
assert_eq!(x, E::VariantB(??));

解决方案

I am going to go on a limb here and say No.


It is possible with just a minor change to the signature though:

fn change_to_variant_b<T>(e: E<T>) -> E<T> {
    match e {
        E::VariantA(t) => E::VariantB(t),
        E::VariantB(t) => E::VariantB(t),
    }
}


It is possible using unsafe:

fn change_to_variant_b<T>(e: &mut E<T>) {
    use std::ptr;

    unsafe {
        match ptr::read(e as *const _) {
            E::VariantA(t) => ptr::write(e as *mut _, E::VariantB(t)),
            E::VariantB(t) => ptr::write(e as *mut _, E::VariantB(t)),
        }
    }
}


It is possible with additional bounds (Default, or Clone):

fn change_to_variant_b<T: Default>(e: &mut E<T>) {
    match std::mem::replace(e, E::VariantA(T::default())) {
        E::VariantA(t) => e = E::VariantB(t),
        E::VariantB(t) => e = E::VariantB(t),
    }
}

这篇关于是否可以将可变引用的值中的变体更改为枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆