I'm just starting out learning Rust, and I've hit a bit of a roadblock;
I'm trying to create a function that initialises the rusty_v8
library. They've given the following code get set up with:
use rusty_v8 as v8;
let platform = v8::new_default_platform().unwrap();
v8::V8::initialize_platform(platform);
v8::V8::initialize();
let isolate = &mut v8::Isolate::new(Default::default());
let scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(scope);
let scope = &mut v8::ContextScope::new(scope, context);
let code = v8::String::new(scope, "'Hello' + ' World!'").unwrap();
println!("javascript code: {}", code.to_rust_string_lossy(scope));
let script = v8::Script::compile(scope, code, None).unwrap();
let result = script.run(scope).unwrap();
let result = result.to_string(scope).unwrap();
println!("result: {}", result.to_rust_string_lossy(scope));
Now, I've set myself the challenge of making this reusable. I want to be able to call an init
function of some sort, which returns a v8::Scope
object, that I can use to execute v8::Script
objects. I've managed to create this function:
pub(crate) fn init<'a>() -> v8::ContextScope<'a, v8::HandleScope<'a, v8::Context>> {
let platform = v8::new_default_platform().unwrap();
v8::V8::initialize_platform(platform);
v8::V8::initialize();
let mut isolate = v8::Isolate::new(Default::default());
let mut scope = v8::HandleScope::new(&mut isolate);
let context = v8::Context::new(&mut scope);
return v8::ContextScope::new(&mut scope, context);
}
So far, I understand how the code should work and why it doesn't. The compiler says for return statement: returns a value referencing data owned by the current function
. This makes sense to me, the isolate
and scope
variables are created within this function. But if I want to use this function as a factory, in other words, to make this function construct a ContextScope
object, the isolate
and scope
objects have to be kept alive. How would I achieve this?