Module glib::variant[][src]

Expand description

Variant binding and helper traits.

Variant is an immutable dynamically-typed generic container. Its type and value are defined at construction and never change.

Variant types are described by VariantType “type strings”.

Although GVariant supports arbitrarily complex types, this binding is currently limited to the basic ones: bool, u8, i16, u16, i32, u32, i64, u64, f64, &str/String, and VariantDict.


use glib::prelude::*; // or `use gtk::prelude::*;`
use glib::{Variant, FromVariant, ToVariant};
use std::collections::HashMap;

// Using the `ToVariant` trait.
let num = 10.to_variant();

// `is` tests the type of the value.

// `get` tries to extract the value.
assert_eq!(num.get::<i32>(), Some(10));
assert_eq!(num.get::<u32>(), None);

// `get_str` tries to borrow a string slice.
let hello = "Hello!".to_variant();
assert_eq!(hello.str(), Some("Hello!"));
assert_eq!(num.str(), None);

// Variant carrying a Variant
let variant = Variant::from_variant(&hello);
let variant = variant.as_variant().unwrap();
assert_eq!(variant.str(), Some("Hello!"));

// Variant carrying an array
let array = ["Hello".to_variant(), "there!".to_variant()];
let variant = Variant::from_array::<&str>(&array);
assert_eq!(variant.n_children(), 2);
assert_eq!(variant.child_value(0).str(), Some("Hello"));
assert_eq!(variant.child_value(1).str(), Some("there!"));

// You can also convert from and to a Vec
let array = vec!["Hello", "there!"].to_variant();
assert_eq!(variant.n_children(), 2);
let vec = <Vec<String>>::from_variant(&array).unwrap();
assert_eq!(vec[0], "Hello");

// Conversion to and from HashMap is also possible
let mut map: HashMap<u16, &str> = HashMap::new();
map.insert(1, "hi");
map.insert(2, "there");
let variant = map.to_variant();
assert_eq!(variant.n_children(), 2);
let map: HashMap<u16, String> = HashMap::from_variant(&variant).unwrap();
assert_eq!(map[&1], "hi");
assert_eq!(map[&2], "there");

// And conversion to and from tuples.
let variant = ("hello", 42u16, vec![ "there", "you" ],).to_variant();
assert_eq!(variant.n_children(), 3);
assert_eq!(variant.type_().to_str(), "(sqas)");
let tuple = <(String, u16, Vec<String>)>::from_variant(&variant).unwrap();
assert_eq!(tuple.0, "hello");
assert_eq!(tuple.1, 42);
assert_eq!(tuple.2, &[ "there", "you"]);

// `Option` is supported as well, through maybe types
let variant = Some("hello").to_variant();
assert_eq!(variant.n_children(), 1);
let mut s = <Option<String>>::from_variant(&variant).unwrap();
assert_eq!(s.unwrap(), "hello");
s = None;
let variant = s.to_variant();
assert_eq!(variant.n_children(), 0);
let s = <Option<String>>::from_variant(&variant).unwrap();



A Dictionary entry.


A generic immutable value capable of carrying various types.



Extracts a value.


Returns VariantType of Self.


Converts to Variant.