繁体   English   中英

为什么 Rust 编译器不够聪明,无法检测变量和 function 同名?

[英]Why Rust compiler is not smart enough to detect the variable and function with same name?

我正在尝试通过传递参数来访问 function 但参数和 function 名称都相同,

fn main(){
    let name = "xyz";
    println!("name: {:?}", name(name));}

fn name(y: &str)-> &str{
    y}

the output says it is expresion and need function to resolve, actually it is a function and it can be resolved by changing the function name, but for now I want to know why is compiler not detecting the function?

error[E0618]: expected function, found `&str`
2 |     let name = "xyz";
  |         ---- `&str` defined here
3 |     println!("name: {:?}", name(name));
  |                            ^^^^------
  |                            |
  |                            call expression requires function

我想知道为什么编译器没有检测到 function?

因为没有什么可检测的。

Rust 不会将函数分离到单独的命名空间中,在大多数情况下,function 只是一个与其他值一样的值。 因为name也可以是一个闭包(它是可调用的),或者一个方法引用,例如

fn foo() {} // "regular" function
fn main() {
    let foo = foo; // local reference to the function
    let foo = Foo::foo; // UFCS
    let foo = || {}; // anonymous function
}

事实上,虽然实现特征仍然不稳定,但最终应该可以通过实现 Fn/FnMut/FnOnce 特征将任何东西变成“函数”(Python 称这个概念为“可调用对象”)。

function 是一个变量。 当您在新的 scope 中使用相同的变量名称时,它会在整个 scope 中使用该新声明。 因此,在main() function 中,您将使用新值"xyz"覆盖变量name 您的代码本质上是"xyz"("xyz")

再举一个例子,这段代码会打印什么?

fn name() {
    println!("hi");
}

fn main() {
    fn name() {
        println!("bye");
    }
    name();
}

它将打印"bye" ,因为它正在调用本地function name

值得注意的例外是在同一个 scope 中重新声明 function (无论是顶级还是在 function 上下文中):

fn name() {
    println!("a");
}
fn name() {
    println!("b");
}
fn main() {
    fn name() {
        println!("c");
    }
    fn name() {
        println!("d");
    }
    name();
}

这会给您两个错误,一个针对您已声明两次的每个 scope。

  |
1 | fn name() {
  | --------- previous definition of the value `name` here
...
4 | fn name() {
  | ^^^^^^^^^ `name` redefined here
  |
  = note: `name` must be defined only once in the value namespace of this module

error[E0428]: the name `name` is defined multiple times
  --> src/main.rs:11:5
   |
8  |     fn name() {
   |     --------- previous definition of the value `name` here
...
11 |     fn name() {
   |     ^^^^^^^^^ `name` redefined here
   |
   = note: `name` must be defined only once in the value namespace of this block

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM