What is a function signature and type?

放肆的年华 提交于 2019-12-02 07:22:21

The signature of a function describes:

  • its name
  • its arguments
  • its result
  • in the case of generic functions, its generic parameters, with potentially specific bounds

For example, if you define:

fn hello(s: &str) {
    println!("Hello {}", s);
}

The function signature is fn hello(&str).


In Rust, each function has a unique type, which cannot be named.

However, if you have a function, you can also coerce it into a generic fn type which does not care about the identity of the function, but only about how it can be used.

For the above function, this generic type is: fn(&str) (or fn(&str) -> () if we wish to be explicit).


This generic type is useful to abstract over multiple functions with a similar signature. For example:

fn add(left: i32, right: i32) -> i32 { left + right }
fn sub(left: i32, right: i32) -> i32 { left - right }

fn select(name: &str) -> fn(i32, i32) -> i32 {
    match name {
        "add" => add,
        "sub" => sub,
        _ => unimplemented!(),
    }
}

fn main() {
    let fun = select("add");
    println!("{} + {} = {}", 1, 2, fun(1, 2));
}

It is close to function pointers in C or C++, however unlike function pointers it cannot be null.

If you need a nullable function, you can use Option<fn(i32, i32) -> i32> instead.


And thus finally we come to this type alias: it's simply a shortcut because the generic fn type is long. Like any other type alias.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!