Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Debugging 如何访问函数';s每次调用位置时';这叫什么?_Debugging_Rust - Fatal编程技术网

Debugging 如何访问函数';s每次调用位置时';这叫什么?

Debugging 如何访问函数';s每次调用位置时';这叫什么?,debugging,rust,Debugging,Rust,我想写一个函数来访问文件和它被调用的位置的行号 它看起来是这样的: fn main(){ 打印_调用_location();//将打印`从第2行调用` 打印_调用_location();//将打印`从第3行调用` } fn打印\u调用\u位置(){ 让呼叫者线号=/*?*/; println!(“从第{}行调用,调用方第{行第}号); } 添加了跟踪调用者功能,使函数能够访问调用者的位置 简短回答:要获取调用函数的位置,请使用#[track_caller]标记函数,并在函数体中使用 根据该答案,

我想写一个函数来访问文件和它被调用的位置的行号

它看起来是这样的:

fn main(){
打印_调用_location();//将打印`从第2行调用`
打印_调用_location();//将打印`从第3行调用`
}
fn打印\u调用\u位置(){
让呼叫者线号=/*?*/;
println!(“从第{}行调用,调用方第{行第}号);
}
添加了
跟踪调用者
功能,使函数能够访问调用者的位置

简短回答:要获取调用函数的位置,请使用
#[track_caller]
标记函数,并在函数体中使用

根据该答案,您的示例如下所示:

#![功能(跟踪呼叫方)]
fn main(){
打印_调用_location();//将打印`从第2行调用`
打印_调用_location();//将打印`从第3行调用`
}
#[追踪来电者]
fn打印\u调用\u位置(){
让caller_location=std::panic::location::caller();
让caller_line_number=caller_location.line();
println!(“从第{}行调用,调用方第{行第}号);
}

更具体地说,该函数有两种行为:

  • 在标记为
    #[track_caller]
    的函数中,它返回一个
    &'static Location添加
    track_caller
    功能,该功能使函数能够访问其调用者的位置

    简短回答:要获取调用函数的位置,请使用
    #[track_caller]
    标记函数,并在函数体中使用

    根据该答案,您的示例如下所示:

    #![功能(跟踪呼叫方)]
    fn main(){
    打印_调用_location();//将打印`从第2行调用`
    打印_调用_location();//将打印`从第3行调用`
    }
    #[追踪来电者]
    fn打印\u调用\u位置(){
    让caller_location=std::panic::location::caller();
    让caller_line_number=caller_location.line();
    println!(“从第{}行调用,调用方第{行第}号);
    }
    

    更具体地说,该函数有两种行为:


    • 在标记为
      #[track_caller]
      的函数中,它返回一个
      &'static Location使用“隐式调用方位置”(隐式调用方位置可能因任何原因不可用/不适合您)的替代方法是使用C方式。
      例如,将函数隐藏在宏后面

      macro_rules! prints_calling_location {
          () => { 
              let caller_line_number = line!();
              println!("called from line: {}", caller_line_number);
          };
      }
      
      fn main() {
          prints_calling_location!(); // prints `called from line: 10`
          prints_calling_location!(); // prints `called from line: 11`
      }
      

      使用“隐式调用方位置”(无论出于何种原因,它可能不可用/不适合您)的另一种方法是使用C方式。 例如,将函数隐藏在宏后面

      macro_rules! prints_calling_location {
          () => { 
              let caller_line_number = line!();
              println!("called from line: {}", caller_line_number);
          };
      }
      
      fn main() {
          prints_calling_location!(); // prints `called from line: 10`
          prints_calling_location!(); // prints `called from line: 11`
      }
      

      您可以手动编写程序宏来完成类似于中的操作。它的工作原理是在运行时解析回溯,您可以手动编写过程宏来完成,如中所示。它通过在运行时解析回溯来工作