每次调用函数时如何访问它的调用位置?

编程入门 行业动态 更新时间:2024-10-26 20:34:15
本文介绍了每次调用函数时如何访问它的调用位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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] ,它具有容易出错的行为,即返回调用位置,而不是调用函数的实际位置,例如:

  • 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()); }

游乐场链接

更多推荐

每次调用函数时如何访问它的调用位置?

本文发布于:2023-11-30 18:03:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   位置

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!