twistezo
twistezo

Reputation: 576

How do I extract a value from a tuple struct?

I have an object of a struct with one field from an external library, which is defined as: pub struct SomeId(pub i64);

Using println! to print the object shows this, for example: SomeId(123)

I created my own struct:

#[derive(Debug)]
pub struct Something {
    pub id: i64,
}

And I'm trying to put value from external struct SomeId to field id in my struct Something:

let test = Something { id: ?? };

or extract value from struct SomeId:

let test: i64 = ??;

Upvotes: 5

Views: 11340

Answers (3)

lukwol
lukwol

Reputation: 264

It's also possible to use struct destructuring to extract value from SomeId.

pub struct SomeId(pub i64);

#[derive(Debug)]
pub struct Something {
    pub id: i64,
}

fn main() {
    let some_id = SomeId(42);
    let SomeId(id) = some_id;
    let test = Something { id: id };
    let test: i64 = id;
}

Link to more examples.

Upvotes: 9

Murali
Murali

Reputation: 3542

May be you are looking for something like the below?

pub struct SomeId(i32);

#[derive(Debug)]
pub struct Something {
    pub id: i32,
}


fn main() {
    let sid = SomeId(10);
    let sth = Something { id: sid.0 };
    println!("{:?}", sth);
}

Playground link

Upvotes: 2

Malice
Malice

Reputation: 1482

You should probably try

let test = Something { id: external_struct.0 };

or, to the second question,:

let test = external_struct.0;

These structs , of the form , struct structname(variables...) are called tuple structs and acts very similar to tuples in rust.

Upvotes: 7

Related Questions