Skip to content

Commit

Permalink
add downcasting example
Browse files Browse the repository at this point in the history
  • Loading branch information
terror committed Jul 8, 2021
1 parent 6df0159 commit 7f5381a
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions examples/downcast.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
extern crate skim;
use skim::prelude::*;

/// This example illustrates downcasting custom structs that implement
/// `SkimItem` after calling `Skim::run_with`.
#[derive(Debug, Clone)]
struct Item {
text: String,
}

impl SkimItem for Item {
fn text(&self) -> Cow<str> {
Cow::Borrowed(&self.text)
}

fn preview(&self, _context: PreviewContext) -> ItemPreview {
ItemPreview::Text(self.text.to_owned())
}
}

pub fn main() {
let options = SkimOptionsBuilder::default()
.height(Some("50%"))
.multi(true)
.preview(Some(""))
.build()
.unwrap();

let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();

tx.send(Arc::new(Item { text: "a".to_string() })).unwrap();
tx.send(Arc::new(Item { text: "b".to_string() })).unwrap();
tx.send(Arc::new(Item { text: "c".to_string() })).unwrap();

drop(tx);

let selected_items = Skim::run_with(&options, Some(rx))
.map(|out| out.selected_items)
.unwrap_or_else(|| Vec::new())
.iter()
.map(|selected_item| (**selected_item).as_any().downcast_ref::<Item>().unwrap().to_owned())
.collect::<Vec<Item>>();

for item in selected_items {
println!("{:?}", item);
}
}

0 comments on commit 7f5381a

Please sign in to comment.