當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。