123456789101112131415161718192021222324252627282930313233343536373839404142 |
- use shared::Data;
- // A example borrowing some Data
- fn something(d: &Data) {
- // Because Data implements Display (It also implements Debug {:?})
- println!("{}", d);
- }
- fn main() {
- // Let's make a primitive
- let my_uint: u32 = 42;
- // Now notice the simplicity of converting from
- let my_uint: Data = Data::from(my_uint);
- let my_int: Data = Data::from(1024_i64);
- let nothing: Data = Data::default(); // Want something empty?
-
- // Ok let's call something now
- something(&my_uint);
- something(&my_int);
- something(¬hing);
- // Directly? Sure!
- println!("uint={} int={}", my_uint, my_int);
- // Let's say we wanted to get it back out (by we know the original type)
- let uint: Result<u32, ()> = my_uint.clone().try_into();
- if let Ok(u) = uint {
- println!("{:?}", u); // Yay, it is a u32
- } else {
- println!("{:?}", my_uint); // We had to clone it above so we can print it down here :)
- }
- // However, the above would fail if we try_into a different type (even something like u64 or u128 will "fail", despite the underlying being a u32)
- // Don't want this? Use the `cast_into` feature (Then the u32 or lower will be casted to u64 or u128, but it only works lower bits to higher bits)
- // We can get a general idea of what the type is, even a loose type like JSON's Number (which could be float or integer or even unsigned integer)
- if my_int.is_number() {
- println!("{} is a number", my_int);
- }
- // Data also supports being used in collections such as Vec<Data> and HashMap<String, Data> (Note: HashMap will require String and Data, if the key is a number it's better to use a Vec)
- // See collection_data_example.rs
- }
|