当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Location.caller用法及代码示例


本文简要介绍rust语言中 std::panic::Location.caller 的用法。

用法

pub fn caller() -> &'static Location<'static>

返回此函数调用者的源位置。如果该函数的调用者被注释,那么它的调用位置将被返回,依此类推,直到堆栈中的第一个非跟踪函数体中的调用。

例子

use std::panic::Location;

/// Returns the [`Location`] at which it is called.
#[track_caller]
fn get_caller_location() -> &'static Location<'static> {
    Location::caller()
}

/// Returns a [`Location`] from within this function's definition.
fn get_just_one_location() -> &'static Location<'static> {
    get_caller_location()
}

let fixed_location = get_just_one_location();
assert_eq!(fixed_location.file(), file!());
assert_eq!(fixed_location.line(), 14);
assert_eq!(fixed_location.column(), 5);

// running the same untracked function in a different location gives us the same result
let second_fixed_location = get_just_one_location();
assert_eq!(fixed_location.file(), second_fixed_location.file());
assert_eq!(fixed_location.line(), second_fixed_location.line());
assert_eq!(fixed_location.column(), second_fixed_location.column());

let this_location = get_caller_location();
assert_eq!(this_location.file(), file!());
assert_eq!(this_location.line(), 28);
assert_eq!(this_location.column(), 21);

// running the tracked function in a different location produces a different value
let another_location = get_caller_location();
assert_eq!(this_location.file(), another_location.file());
assert_ne!(this_location.line(), another_location.line());
assert_ne!(this_location.column(), another_location.column());

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::panic::Location.caller。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。