什么是函数签名和类型? [英] What is a function signature and type?

查看:39
本文介绍了什么是函数签名和类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面研究的Scheme解释器中找到了类型别名.在评估AST时,它会将功能识别为本机支持的功能或用户定义的功能.我理解 Enum 定义的第二部分,但是第一部分使我难以理解.

I found the type alias below in an Scheme interpreter I'm studying. While evaluating the AST, it recognizes a function either as a natively supported function, or as a user defined function. I understand the second part of the Enum definition, but the first part eludes me.

pub enum Function {
    Native(ValueOperation),
    Scheme(Vec<String>, Vec<Value>, Rc<RefCell<Environment>>),
}


type ValueOperation = fn(&[Value], Rc<RefCell<Environment>>) -> Result<Value, RuntimeError>;

此类型别名如何工作?这个定义是否表示 ValueOperation 只是函数签名的简写?我在官方文档/书中找不到任何提及该习惯用语的地方.

How does this type alias work? Does this definition say that a ValueOperation is just a shorthand for a function signature? I was unable to find any mention of this idiom in the official docs/books.

为函数签名定义类型别名的目的是什么?您可以做什么"呢?它是某种函数指针吗?

What's the purpose of defining a type alias for a function signature? What can you "do" with it? Is it some sort of a function pointer?

推荐答案

函数的签名描述:

  • 它的名字
  • 其论点
  • 其结果
  • 对于泛型函数,其泛型参数具有潜在的特定范围

例如,如果您定义:

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

函数签名为 fn hello(& str).

在Rust中,每个函数都有唯一的类型,无法命名.

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

但是,如果您有一个函数,也可以将其强制为通用的 fn 类型,该类型不关心函数的身份,而只关心如何使用它.

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.

对于上面的函数,此通用类型为: fn(& str)(或 fn(& str)->()明确).

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));
}


它与C或C ++中的函数指针非常接近,但是与函数指针不同,它不能为null.


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

如果需要可为空的函数,则可以使用 Option< fn(i32,i32)->i32> 代替.

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

因此,我们终于有了这种类型别名:它只是一种捷径,因为通用的 fn 类型很长.像其他任何类型的别名一样.

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.

这篇关于什么是函数签名和类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆