不能在内部函数中使用外部类型参数的理由是什么? [英] What is the rationale for not being able to use the outer type parameter within an inner function?

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

问题描述

我正在尝试创建一个递归内部函数,它将打印链表中的所有元素:

I'm trying to create a recursive inner function that will print all elements in a linked list:

 fn print_stack(&self) {
    fn print_nodes(head: &Option<Box<Node<T>>>) {
        match head {
            Some(ref p) => {
                println!("{:?}",p.data);
                print_nodes(head.next);
            },
        }
   };
   print_nodes(&self.head);
}

编译器产生以下错误

can't use type parameters from outer function; try using a local  type parameter instead.

为什么这是一个错误?

推荐答案

来自 Rust编译器错误索引:

内部项不会从它们嵌入的函数中继承类型参数.

E0401

Inner items do not inherit type parameters from the functions they are embedded in.

[...]

函数内的项基本上和顶级项一样,只是它们只能在它们所在的函数中使用.

Items inside functions are basically just like top-level items, except that they can only be used from the function they are in.

对此有几种解决方案.

[...]

对于通用项目,您可以复制参数:

For a generic item, you can copy over the parameters:

[...]

我会由此得出结论,函数内的项目也被编译为顶级项目.允许对外部函数类型参数的引用将允许具有相同名称的两个不同的函数定义,函数本身没有任何类型参数可以消除歧义,因此需要名称修改更改.制作一个小测试程序证实了这一点:

I would conclude from this that items inside functions are also compiled as top-level items. Allowing references to the outer function type parameters would allow two different function definitions with the same name, without any type parameters on the function itself to disambiguate, so would require name mangling changes. Making a small test program confirms this:

struct Foo<T>(T);
impl <T> Foo<T> {
    pub fn bar() {
        fn baz() { }
        baz();
    }
}
fn main() {
    Foo::<i32>::bar();
    Foo::<u32>::bar();
}

编译这个并在生成的输出上调用 nm 显示了 bar 的两个定义,以及 baz 的单个定义.

Compiling this and calling nm on the generated output shows two definitions of bar, and a single definition of baz.

可以按照您期望的方式更改 Rust,但首先需要对其进行设计,并且感知到的收益必须大于实施它的成本.鉴于可用的解决方法,感知的好处可能很小.在您的情况下,如该页面所示,解决方法是也为内部函数指定类型参数.

It's possible to change Rust in the way you expect, but it would need to be designed first, and the perceived benefits must outweigh the cost to implement it. Given the available workarounds, the perceived benefits may be small. In your case, as indicated on that page, the workaround is to specify the type parameters for the inner function as well.

这篇关于不能在内部函数中使用外部类型参数的理由是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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