The proper handling of JavaScript closures is essential to any JavaScript project. In React projects specifically, closures can manifest themselves […]
filter()
method in JavaScriptLearn about the array filter() method, from its basic syntax and use cases to more advanced techniques like chaining with map() and reduce().
CSS has come a long way, making vertical alignment easier than ever. Learn about this concept and explore some of the best CSS vertical alignment techniques.
Use Flutter to build browser-based app demos that help clients visualize the product, speed up buy-in, and close deals faster.
2 Replies to "How to define higher-order functions in Rust"
Thanks for a great article. In python I can pass a method that is bound to an object. Can I do the equivalent in rust?
Hello Giles. A method in Rust is just a function, which also takes a first `self` parameter (similarly to Python). Hence, passing a method is just a matter of using the right types in the function signatures:
pub struct Greeter {
greeting: String
}
impl Greeter {
fn greet(&self, name: String) -> String {
return format!(“{}, {}”, self.greeting, name);
}
}
fn call(name: String, fun: fn(&Greeter, String) -> String) -> String {
let greeter = Greeter { greeting: “Hello”.to_string() };
return fun(&greeter, name);
}
fn main() {
println!(“{}”, call(“Giles”.to_string(), Greeter::greet));
}