如何将 rust 结构“转换”为另一个相同类型(相同的字段/布局)而不复制所有成员

问题描述 投票:0回答:1

我在一个模块中有一个私有类型,它与另一种类型具有相同的字段。我无法相互导入(以某种方式共享类型),因为这会导致循环依赖,并且重构以允许这一点将非常复杂。

为了清楚起见,两个模块中的结构如下所示:

struct Args {
   pub a: String,
   pub b: String,
   pub c: Option<PathBuf>,
}

在某些情况下,我可以“消耗”其中一项,所以我会在字段之间进行

std::mem::swap

但是在无法消费的情况下,我需要发送其他类型的引用,为了调用函数而创建中间对象并来回交换是很麻烦的

例如在这样的情况下:

pub struct Args {
     pub a: String,
     pub b: String,
     pub c: Option<PathBuf>
}
fn main() {
  let args = crate::Args::default(); // this module Args
  crate::work(&args); // works obviously

  mod2::mod2_work(&args); // doesn't work

  // how to avoid this?
  let m2_args = mod2::work::Args { ... } // copy/clone from this args;

  mod2::mod2_work(&m2_args); // works

}

fn work(args: &Args) { } // this module args


// module 2 (different but same "Args")
// for the sake of this example assume even the same file
pub mod mod2 {
  pub struct Args {
     pub a: String,
     pub b: String,
     pub c: Option<PathBuf>
  }

  pub fn mod2_work(args: &mod2::Args) { } // module 2 args
}



rust casting move-semantics
1个回答
2
投票

如果 Args 和 mod2::Args 相同(相同的字段名称,相同的类型), 定义第二个 Args 没有任何价值。

您可以给它起别名:

type MyArgs = mod2::Args;

或者只是纳入范围:

use mod2::Args as MyArgs;

然后将其视为你自己的类型。

话虽如此,有 mem::transmute - 黑魔法可以满足你的要求。

© www.soinside.com 2019 - 2024. All rights reserved.