代码之家  ›  专栏  ›  技术社区  ›  Nurbol Alpysbayev

如何去掉(移出)包含大数据结构类型的结构字段?

  •  0
  • Nurbol Alpysbayev  · 技术社区  · 5 年前

    我有一个很大的结构:

    struct VeryLargeStructure {
        // many tens of fields here
    }
    

    以及另一个包含在字段中的结构:

    struct A {
      v: VeryLargeStructure 
    }
    

    如何从 v 字段。。。

    let a = A{/* ... */}
    let b = a.v;
    

    ... 不需要构造一个新的VeryLargeStructure实例 对于 a.v ,因为那将是没有性能和无用的?

    我知道 mem::replace mem::swap ,但不满足上述要求。

    我更喜欢安全的方法,但我怀疑没有,所以我也准备好了 unsafe 一个。

    1 回复  |  直到 5 年前
        1
  •  4
  •   SCappella    5 年前

    顺便说一下,你已经写过的作品。这转让了 a.v b 使无效 a (旧变量不再存在)。这意味着我们不需要用有效的数据替换取出的数据。这是拥有所有权相对于可变访问的好处之一。

    let a = A {
        v: VeryLargeStructure {/* ... */},
    };
    let b = a.v;
    // Now `b` has ownership of what was once `a.v`.
    // `a` no longer exists as a single entity,
    // but you could extract other fields too if you wish.
    // E.g. `let c = a.w` if `w` is some other field of `a`.
    

    在上下文中,

    struct VeryLargeStructure {
        // many tens of fields here
    }
    
    struct A {
        v: VeryLargeStructure,
    }
    
    fn main() {
        let a = A {
            v: VeryLargeStructure {/* ... */},
        };
        let b = a.v;
    }
    

    (playground)


    有点脱色的版本是 destructuring . 它可以方便地同时提取多个字段。不过,就一个领域而言, let b = a.v; 可能是首选,因为它更简单、更清晰。

    struct VeryLargeStructure {
        // many tens of fields here
    }
    
    struct A {
        v: VeryLargeStructure,
    }
    
    fn main() {
        let a = A {
            v: VeryLargeStructure {/* ... */},
        };
        let A { v: b } = a;
    }
    

    (playground)


    注意,如果 A 工具 Drop ,它必须保留所有油田的所有权。这就意味着你不能不更换就搬出去。替换数据(例如 mem::replace )不过,很好。