data_example.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. use shared::Data;
  2. // A example borrowing some Data
  3. fn something(d: &Data) {
  4. // Because Data implements Display (It also implements Debug {:?})
  5. println!("{}", d);
  6. }
  7. fn main() {
  8. // Let's make a primitive
  9. let my_uint: u32 = 42;
  10. // Now notice the simplicity of converting from
  11. let my_uint: Data = Data::from(my_uint);
  12. let my_int: Data = Data::from(1024_i64);
  13. let nothing: Data = Data::default(); // Want something empty?
  14. // Ok let's call something now
  15. something(&my_uint);
  16. something(&my_int);
  17. something(&nothing);
  18. // Directly? Sure!
  19. println!("uint={} int={}", my_uint, my_int);
  20. // Let's say we wanted to get it back out (by we know the original type)
  21. let uint: Result<u32, ()> = my_uint.clone().try_into();
  22. if let Ok(u) = uint {
  23. println!("{:?}", u); // Yay, it is a u32
  24. } else {
  25. println!("{:?}", my_uint); // We had to clone it above so we can print it down here :)
  26. }
  27. // 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)
  28. // 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)
  29. // 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)
  30. if my_int.is_number() {
  31. println!("{} is a number", my_int);
  32. }
  33. // 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)
  34. // See collection_data_example.rs
  35. }