Is it possible to make this compile? I would like to avoid this ugly "as FunctionType"
use_function() is supposed to take either a function pointer directly, or something that can be converted into a function pointer.
fn main() {
println!("Hello, world!");
use_function(Function::Default);
use_function(default_function); // Is it possible to make this compile?
use_function(default_function as FunctionType); // this works, but is ugly
}
fn use_function<F: IntoFunction>(format_function: F) {
unimplemented!("use_function");
}
fn default_function() -> Result<(), std::io::Error> {
unimplemented!("default_function");
}
fn other_function() -> Result<(), std::io::Error> {
unimplemented!("other_function");
}
pub trait IntoFunction {
fn format_function(self, other: bool) -> FunctionType;
}
enum Function {
Default,
Custom(FunctionType, FunctionType),
}
impl IntoFunction for Function {
fn format_function(self, other: bool) -> FunctionType {
if other {
match self {
Self::Default => other_function,
Self::Custom(_, method2) => method2,
}
} else {
match self {
Self::Default => default_function,
Self::Custom(method1, _) => method1,
}
}
}
}
pub type FunctionType = fn() -> Result<(), std::io::Error>;
impl IntoFunction for fn() -> std::result::Result<(), std::io::Error> {
fn format_function(self, _other: bool) -> FunctionType {
self
}
}
// impl IntoFunction for FunctionType {
// fn format_function(self, _other: bool) -> FunctionType {
// self
// }
// }
Errors:
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `fn() -> std::result::Result<(), std::io::Error> {default_function}: IntoFunction` is not satisfied
--> src/main.rs:4:18
|
4 | use_function(default_function); // FIXME
| ^^^^^^^^^^^^^^^^ the trait `IntoFunction` is not implemented for `fn() -> std::result::Result<(), std::io::Error> {default_function}`
...
8 | fn use_function<F: IntoFunction>(format_function: F) {
| ------------ required by this bound in `use_function`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`
To learn more, run the command again with --verbose.