Expand description
Variant data type. Variant type used for communications and other purposes. A good example of a Variant type used in a similar application is in the locka99/opcua implementation found here: https://github.com/locka99/opcua/blob/master/lib/src/types/variant.rs
Notes:
- Objects are stored in IndexMap, not HashMap, to maintain order for serialization to bytes.
Examples:
Array
use mechutil::variant::VariantValue;
// Initialize an empty Vec<VariantValue> for the array elements.
let mut array_elements: Vec<VariantValue> = Vec::new();
// Add some data to the array.
// For example, let's add a mix of integers and strings.
array_elements.push(VariantValue::Int32(10));
array_elements.push(VariantValue::String("Hello".to_string()));
array_elements.push(VariantValue::Real64(3.14));
// Now, create a VariantValue::Array with this vector.
let mut array = VariantValue::Array(array_elements);
// To demonstrate accessing and modifying the array,
// let's add another element to the VariantValue::Array.
// Direct manipulation like this requires knowing the exact type,
// so in real-world scenarios, pattern matching or direct access with caution is advisable.
if let VariantValue::Array(ref mut vec) = array {
// Add a new element to the array.
vec.push(VariantValue::Bit(true));
}
println!("{:?}", array);
Object
use indexmap::IndexMap;
use mechutil::variant::VariantValue;
// Initialize an empty IndexMap.
let mut map: IndexMap<String, VariantValue> = IndexMap::new();
// Add some data to the map.
// For example, let's add a string and an integer.
map.insert("key1".to_string(), VariantValue::String("value1".to_string()));
map.insert("key2".to_string(), VariantValue::Int32(42));
// Now, create a VariantValue::Object with this map.
let mut ret = VariantValue::Object(Box::new(map));
// To demonstrate accessing and modifying the object,
// let's add another value to the object.
// Access the IndexMap directly from the VariantValue::Object variant.
// Note: You need to do pattern matching or use if let / match statements
// for safer access in real-world scenarios. This example assumes the direct access for simplicity.
if let VariantValue::Object(ref mut boxed_map) = ret {
// Insert a new key-value pair.
boxed_map.insert("key3".to_string(), VariantValue::Real64(3.14));
}
println!("{:?}", ret);
Enums§
- Variant
Type Id - The variant type id is the type of the variant but without its payload.
- Variant
Value - Stores a variant value as found in a remote industrial controller.