解构 Rust 中的嵌套结构。

huangapple go评论139阅读模式
英文:

Destructuring nested structs in Rust

问题

在Rust中,可以在嵌套的情况下解构结构体吗?

struct S2 {
    field1: i64,
    field2: i64,
}

struct S1 {
    field1: String,
    field2: S2,
}

let s1 = S1 {
    field1: String::from("hello"),
    field2: S2 {
        field1: -1,
        field2: 0,
    }
}

let S1 {
    field1,
    field2: S2 {
        field1: field1_s2,
        ..
    }
} = s1;

我会假设答案是"不可以",但以防有类似的方法,或者我的语法可能有问题。

英文:

Is it possible to destructure structs in Rust when they are nested?

struct S2 {
    field1: i64,
    field2: i64,
}

struct S1 {
    field1: String,
    field2: S2,
}

let s1 = S1 {
    field1: String::from("hello"),
    field2: S2 {
        field1: -1,
        field2: 0,
    }
}

let S1 {
    field1,
    S2 {
        field1: field1_s2,
        ..
    }
} = s1;

I would assume the answer is "no" - but just in case there is a way to do something similar, or perhaps my syntax is wrong.

答案1

得分: 7

这是可能的,但你需要指定字段名称:

let S1 {
    field1,
    field2: S2 {
        field1: field1_s2, ..
    },
} = s1;
英文:

Yes, this is possible, but you need to specify the field name:

let S1 {
    field1,
    field2: S2 {
        field1: field1_s2, ..
    },
} = s1;

huangapple
  • 本文由 发表于 2023年8月4日 20:40:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定