每次调用函数时如何访问它的调用位置? [英] How can I access a function's calling location each time it's called?

查看:132
本文介绍了每次调用函数时如何访问它的调用位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to write a function that accesses the file and line number of the location in which it gets called.

它看起来像这样:

fn main() {
    prints_calling_location(); // would print `called from line: 2`
    prints_calling_location(); // would print `called from line: 3`
}

fn prints_calling_location() {
    let caller_line_number = /* ??? */;
    println!("called from line: {}", caller_line_number);
}


推荐答案

RFC 2091:隐式调用者位置添加了 track_caller 功能这使功能可以访问其调用者的位置。

RFC 2091: Implicit caller location adds the track_caller feature which enables a function to access the location of its caller.

简短答案:要获取调用函数的位置,请在#[track_caller] 中进行标记,然后使用 std :: panic ::位置::呼叫者

Short answer: to obtain the location in which your function gets called, mark it with #[track_caller] and use std::panic::Location::caller in its body.

在该答案之后,您的示例将如下所示:

Following from that answer, your example would look like this:

#![feature(track_caller)]

fn main() {
    prints_calling_location(); // would print `called from line: 2`
    prints_calling_location(); // would print `called from line: 3`
}

#[track_caller]
fn prints_calling_location() {
    let caller_location = std::panic::Location::caller();
    let caller_line_number = caller_location.line();
    println!("called from line: {}", caller_line_number);
}

游乐场链接

更具体地说,函数 std :: panic :: Location :: caller 有两种行为:

More specifically, the function std::panic::Location::caller has two behaviors:


  • 在一个函数内标记为#[track_caller] ,它会返回&'static Location<'static>

  • 在一个没有#[track_caller] <的函数中,列出调用函数的文件,行号和列号。 / code>,它具有容易出错的行为,即返回调用位置,而不是调用函数的实际位置,例如:

  • Within a function marked #[track_caller], it returns a &'static Location<'static> which you can use to find out the file, line number, and column number in which your function gets called.
  • Within a function that doesn't have #[track_caller], it has the error-prone behavior of returning the actual location where you've invoked it, not where your function gets called, for example:

#![feature(track_caller)]

fn main() {
    oops();
    // ^ prints `line: 10` instead of the expected `line: 4`
}

// note: missing #[track_caller] here
fn oops() {
    println!("line: {}", std::panic::Location::caller().line());
}

游乐场链接

这篇关于每次调用函数时如何访问它的调用位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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