Reputation: 1018
In Rust, is it possible to parse a String whose contents is a function, into a function? For example, consider:
let str_function = "fn add_one(x: f64) -> f64{x+1}".to_string();
I'd like to parse that string into an actual function to be used. I know Rust doesn't have anything like Python's eval(), but if I know that the function should take only one parameter, x: f64
and output f64
, it could in theory be possible. Something like this (where I put Box because I don't think it would be possible without Box for sure):
let a: Box<dyn Fn(f64)->f64> = Box::new(str_function.parse::<dyn Fn(f64)->f64>().unwrap());
Is that possible in Rust?
Upvotes: 0
Views: 467
Reputation: 97
The answer is no if you want to use the parse method on a string at runtime to create a callable function. There isn't a convenient way to do that with languages like c or rust, because you always need to hop through the hoop of compilation. From what I can tell that is what you want to do, and on that assumption I recommend you follow the advice of the people who have commented.
The story is slightly different if you want to transform a static string into code. String::parse
can be used to parse any type that implements FromStr
, and as it happens it is implemented for TokenStream
. So as a point of interest: you can technically parse a string of a function into a callable function. Just not at runtime, and it requires the use of procedural macros(see The Reference for an example).
Upvotes: 1