-2

Code:

use std::fmt::Debug;
use std::any::Any;

fn any_to_u16(value: &dyn Any)
{
    let v = value as u16;
}

fn main() 
{
    let x = true;
    any_to_u16(&x);
}

Erorr :

error[E0606]: casting `&(dyn std::any::Any + 'static)` as `u16` is invalid
 --> src/lib.rs:6:13
  |
6 |     let v = value as u16;
  |             ^^^^^^^^^^^^
  |
  = help: cast through a raw pointer first

Playground How to fix?

Boiethios
  • 38,438
  • 19
  • 134
  • 183
Michał Hanusek
  • 199
  • 3
  • 13

1 Answers1

1

You must use Any::downcast_ref:

use std::any::Any;

fn any_to_u16(value: &dyn Any)
{
    if let Some(value) = value.downcast_ref::<bool>().map(|b| *b as u16) {
        // value is a `bool`
        assert_eq!(value, 1);
    }
}

fn main() 
{
    let x = true;
    any_to_u16(&x);
}
Boiethios
  • 38,438
  • 19
  • 134
  • 183
  • Given the comments I think the OP actually wants to use ˋTryInto`. In any case, this function in no way works for any type. – mcarton Feb 21 '20 at 18:36