本文简要介绍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 Location.column用法及代码示例
- Rust Location.line用法及代码示例
- Rust Location.file用法及代码示例
- Rust Location用法及代码示例
- Rust LocalKey用法及代码示例
- Rust LowerExp用法及代码示例
- Rust LowerHex用法及代码示例
- Rust LinkedList.push_front用法及代码示例
- Rust LinkedList.remove用法及代码示例
- Rust LineWriter.new用法及代码示例
- Rust LinkedList.front用法及代码示例
- Rust Lazy用法及代码示例
- Rust Lazy.new用法及代码示例
- Rust LineWriter用法及代码示例
- Rust LinkedList.is_empty用法及代码示例
- Rust Lazy.force用法及代码示例
- Rust LinkedList.back_mut用法及代码示例
- Rust LineWriter.with_capacity用法及代码示例
- Rust LinkedList.pop_front用法及代码示例
- Rust LinkedList.new用法及代码示例
- Rust LinkedList.clear用法及代码示例
- Rust LinkedList.iter_mut用法及代码示例
- Rust LinkedList.drain_filter用法及代码示例
- Rust LinkedList.back用法及代码示例
- Rust LinkedList.front_mut用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::panic::Location.caller。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。