簡體   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