Taaitaaiger / jlrs

Julia bindings for Rust
MIT License
430 stars 21 forks source link

[Question] How to work with a DataType wrapped in a Value? #74

Closed Michael-Jing closed 1 year ago

Michael-Jing commented 1 year ago

Hi Thomas, please forgive me if this question is silly. My context is that rust code will receive a ndarray from julia, then the first thing rust code need to is check the datatype of the ndarray, which can be achieved by calling element_type(). Then the rust code need to know whether the type is Int32 or Bool, etc, I'm stuck at this point currently, because I don't know how to get the internal content out of a value nor how to construct a Value literal to do pattern matching. Please help if it's convenient, in the mean time, I'll try to dig into the code to see if I can figure it out. Thanks!

Taaitaaiger commented 1 year ago

If the element type is a type like Int32 or Bool, the Value returned by Array::element_type is a DataType. To check if the element type is an Int32 or Bool you can call DataType::is with the corresponding rust type:

let arr: Array = fn_that_returns_an_array();
let element_type = arr.element_type().cast::<DataType>().unwrap();

if element_type.is::<bool>() {
    // bool-specific code
} else if element_type.is::<i32>() {
    // i32-specific code
}
Michael-Jing commented 1 year ago

it works, thank you!