You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在struct中存储复合数据且避免拷贝?

如何避免将Thing存入Holder时的拷贝操作?

原代码

struct Holder:
    var thing: Thing
    fn __init__(inout self, owned thing: Thing):
        self.thing = thing
        pass

struct Thing:
    fn __init__(inout self):

thing = Thing()
Holder(thing^)

运行报错

error: Expression [59]:8:22: value of type 'Thing' cannot be copied into its destination
self.thing = thing

预期逻辑

  • ^用于转移所有权,模块作用域不再拥有thing
  • __init__以owned类型接收Thing

已知实现__copyinit__可以让代码运行,但希望避免拷贝,该怎么做?

对比Rust版本(可正常编译运行):

struct Holder {
    thing: Thing
}

struct Thing {}


fn main() {
    Holder { thing: Thing {} };
}

解决方案

修改Holder的__init__方法中的赋值语句,给参数thing加上所有权转移操作符^,直接转移所有权而非拷贝:

fn __init__(inout self, owned thing: Thing):
    self.thing = thing^
    pass

原理:即便参数是owned类型,直接赋值时语言仍会尝试执行拷贝操作;加上^后,会将参数thing的所有权直接转移给self.thing,完全符合最初的所有权转移预期,无需拷贝。

内容的提问来源于stack exchange,提问作者Max Heiber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:15:26