我有一个struct:
pub struct OneDLookup <T: PartialOrd + Sub + Add + Copy + Clone, U: Add + Sub + Copy + Clone>{
breakpoints: Vec<T>,
values: Vec<U>,
last_diff_bp: f64, //ignore these, they are not important to this question
last_diff_values: f64,
first_diff_bp: f64,
first_diff_values: f64,
}
字符串
这将作为一个查找表,但是有两个重要的事情必须是正确的这个结构:
断点必须按升序排列,例如1、5、7、9,而不是任何其他顺序。断点和值必须具有相同的长度。
有没有可能在编译时(或者在编写时使用rust-analyzer更好)在宏中检查这些?恐怕不是。
我对生 rust 还是个新手,所以我还在学习细节。
我尝试基于vec!()
宏创建一个不起作用的小宏,看看我是否能理解那里做了什么,但不幸的是我不知道:
macro_rules! create_1d_lookup {
(($($bps:expr,)*); ($($vals:expr,)*)) => (
$crate::my_crate::OneDLookup::new(vec![$($bps),+], vec![$($vals),+])
);
}
型
OneDLookup::new()将断点和值向量作为参数。
此结构是常量,初始化后不会改变。
1条答案
按热度按时间7tofc5zh1#
您可以通过创建一个
const
来实现这一点,该const
运行一些逻辑来验证不变量是否被维护,如果不变量被破坏,则会出现异常。死机将被转换为编译失败:字符串
不幸的是,这是一个单体化后的错误,这意味着它不会出现在
cargo check
中,只会出现在cargo build
中。