带有多个&符号的程序工作正常 [英] Program with multiple ampersand works fine

查看:34
本文介绍了带有多个&符号的程序工作正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序运行正常:

pub fn foo(_v: &str) -> bool {
    false
}

fn main() {
    let f = "hello world";
    println!("{}", foo(&&&&f)); // note the number of & here
}

事实上,它可以传递任意数量的&.我应该如何解释正在发生的事情?

In fact it works on passing any number of &. How should I interpret what is going on ?

我的 rust 版本:

My rust version:

$ rustc --version
rustc 1.32.0-nightly (13dab66a6 2018-11-05)

推荐答案

来自 Rust 书:

Deref 强制是 Rust 对参数执行的一种便利功能和方法.Deref 强制将引用转换为类型将 Deref 实现为对 Deref 可以的类型的引用将原始类型转换为.Deref 强制自动发生当我们将特定类型值的引用作为参数传递时到与参数类型不匹配的函数或方法函数或方法定义.对 deref 方法的调用序列将我们提供的类型转换为参数需要的类型.

Deref coercion is a convenience that Rust performs on arguments to functions and methods. Deref coercion converts a reference to a type that implements Deref into a reference to a type that Deref can convert the original type into. Deref coercion happens automatically when we pass a reference to a particular type’s value as an argument to a function or method that doesn’t match the parameter type in the function or method definition. A sequence of calls to the deref method converts the type we provided into the type the parameter needs.

所以基本上,在函数参数中,编译器会自动删除任何写入或隐含的 & 直到它获得可以传递给函数的类型.

So basically, in function arguments the compiler will automatically remove any & written or implied until it gets to a type that can be passed to the function.

这篇关于带有多个&符号的程序工作正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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