什么允许函数在返回参数时隐式取消引用参数? [英] What allows a function to implicitly dereference an argument when it's returned?

查看:38
本文介绍了什么允许函数在返回参数时隐式取消引用参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 如何在不将可变引用传递给函数的情况下重新借用它?,OP 有一个类似的函数:

While reading How can I reborrow a mutable reference without passing it to a function?, the OP had a function like:

fn deref<'a, 'b: 'a, T>(t: &'a mut &'b mut T) -> &'a mut T {
    *t
}

这对我来说很有意义.但是,他们也指出不需要在正文 * 中显式取消引用:

This makes sense to me. However, they also pointed out that the explicit dereference in the body * wasn't required:

fn deref<'a, 'b: 'a, T>(t: &'a mut &'b mut T) -> &'a mut T {
    t
}

这编译了,我不知道为什么.我熟悉自动取消引用,但我的印象是只对函数参数起作用,而不是返回值.

This compiles, and I don't know why. I'm familiar with automatic dereferencing, but I was under the impression that only came into play with function arguments, not return values.

推荐答案

阅读 相关文档,似乎 Deref 转换总是根据需要进行多次 - 无论何时需要.Deref 拉取的唯一真正时髦的额外技巧是它也对 self 参数起作用.

Reading the relevant docs, it seems that the Deref conversion always happens as many times as it needs to - wherever it needs to. The only really funky additional trick that Deref pulls is that it also works magic on self arguments.

以下代码片段都有效 - 此处的表达式绝对不限于参数或返回值.

The following snippets both work - and the expressions here are definitely not constrained to be arguments or return values.

// &&&&1 gets dereferenced to &i32 from &&&&i32
let x: &i32 = &&&&1;
let x: (&i32,) = (&&&&1,);

这类事情唯一的问题是 Deref 仅适用于 &U 形式的类型,所以类似于 &1 永远不能从 i32 强制转换为 &i32,即使 &&1 可以从 强制转换&&i32&i32.

The only gotcha with this sort of thing that remains is that Deref only applies to types of the form &U, so something like &1 can never be coerced to &i32 from i32, even if &&1 can be coerced from &&i32 to &i32.

作为旁注,我意识到类型归属有点特殊,但似乎 Deref 并没有在那里进行转换.我不确定它是否是设计使然,或者我是否只是误解了某些东西.以下不起作用.

As a side note, I realize that type ascriptions are a bit special, but it seems Deref doesn't do conversions there. I'm not sure if it is by design or not, or if I'm just misunderstanding something. The following doesn't work.

#![feature(type_ascription)]

// ....

let x = &&1i32: &i32;

基于此评论(以及非常相关的它起源的线程),看起来这只是一个类型归属问题.目前看来,类型归属的实现是没有强制,但几乎所有人都同意这不应该是这种情况(事实上,类型归属的一个很好的用例是暗示要应用强制的编译器).

Based on this comment (and the very relevant thread from which it originates), it looks like this is just a type ascription issue. It appears that for now, type ascription is implemented without coercions, but almost everyone agrees that that should not be the case (in fact, one of the good use cases of type ascriptions would be to hint to the compiler which coercions to apply).

这篇关于什么允许函数在返回参数时隐式取消引用参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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