How can I convert the type returned value from hdk::get_entry(&address) into struct without parsing data to end-user.
I’m a beginner in Rust and hope anybody help me in this.
Thank you
How can I convert the type returned value from hdk::get_entry(&address) into struct without parsing data to end-user.
I’m a beginner in Rust and hope anybody help me in this.
Thank you
Hello @Rzan and welcome to the forum! Let’s see if I understand you correctly: hdk::get_entry(&address)
returns a ZomeApiResult<Option<Entry>>
but you actually want the return value to be in the Rust type that it was when you committed the entry, right?
If that’s true, then there’s a helper function called hdk::util::get_as_type()
. If you use this function, it’ll convert automatically back into the Rust struct. Note that you do have to specify which type of struct; Holochain isn’t yet smart enough to figure that out for you based on the entry type. So it would look like:
let person = hdk::util::get_as_type<Person>(&person_address)?;
(@freesig please check my Rust code cuz I am still so green )
I’m really grateful @pauldaoust, it is exactly what I’m looking for
The syntax like this
let person = get_as_type::<Person>(&person_address)?;
I added also these two lines ::
#![feature(try_from)]
use std::convert::TryFrom;
If you are just returning that person you can also just do:
get_as_type::<Person>(&person_address)
on the last line
I love learning stuff from the people I’m trying to help out. Thanks @Rzan for showing me the proper syntax, reminding me you need TryFrom
, and @freesig for showing how you can do some magical type conversion (I still have no clue about when casts and conversions need to be explicit).
Actually if your function returns ZomeApiResult<Person>
then you don’t need the ::<Person>
.
So it could just be:
fn retrieve_person(address: Address) -> ZomeApiResult<Person> {
hdk::utils::get_as_type(address)
}