example_eval/
example_eval.rs

1// Copyright 2022 The Evcxr Authors.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE
5// or https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use evcxr::Error;
9use evcxr::EvalContext;
10
11fn main() -> Result<(), Error> {
12    // You must call ```evcxr::runtime_hook()``` at the top of main, otherwise
13    // the library becomes a fork-bomb.
14    evcxr::runtime_hook();
15
16    let (mut context, outputs) = EvalContext::new()?;
17    context.eval("let mut s = String::new();")?;
18    context.eval(r#"s.push_str("Hello, ");"#)?;
19    context.eval(r#"s.push_str("World!");"#)?;
20    context.eval(r#"println!("{}", s);"#)?;
21
22    // For this trivial example, we just receive a single line of output from
23    // the code that was run. In a more complex case, we'd likely want to have
24    // separate threads waiting for output on both stdout and stderr.
25    if let Ok(line) = outputs.stdout.recv() {
26        println!("{line}");
27    }
28
29    Ok(())
30}