When there's an error in an associated constant, the default error message doesn't contain enough context for me to find the actual problem. Is there any way to get rustc
to say what the values of the type parameters were when the error occurred?
As a somewhat contrived example, consider the code below. The errors are quite legitimate, because page4
has been declared with a header type too big for the page, but there's no indication in the error as to the root cause, which is that an incompatible type parameter was specified.
use std::mem;
use std::marker::PhantomData;
const PAGE_SIZE:usize = 4096;
struct Page<Head, Rec> {
#[allow(dead_code)]
bytes: [u8;PAGE_SIZE],
head:PhantomData<Head>,
rec:PhantomData<Rec>
}
impl<Head,Rec> Page<Head,Rec> {
const PAYLOAD_SIZE:usize = PAGE_SIZE - mem::size_of::<Head>();
const CAPACITY:usize = Self::PAYLOAD_SIZE / mem::size_of::<Rec>();
fn get_capacity(&self)->usize { Self::CAPACITY }
fn new()-> Self { Page{ bytes: [0u8; PAGE_SIZE], head:PhantomData, rec:PhantomData }}
}
fn main() {
let page1:Page<usize,usize> = Page::new();
println!("Page 1 capacity: {:?}", page1.get_capacity());
let page2:Page<usize,[usize;200]> = Page::new();
println!("Page 2 capacity: {:?}", page2.get_capacity());
let page3:Page<usize,[usize;800]> = Page::new();
println!("Page 3 capacity: {:?}", page3.get_capacity());
let page4:Page<[usize;600], usize> = Page::new();
println!("Page 4 capacity: {:?}", page4.get_capacity());
}
Errors:
Compiling playground v0.0.1 (/playground)
error: any use of this value will cause an error
--> src/main.rs:14:32
|
14 | const PAYLOAD_SIZE:usize = PAGE_SIZE - mem::size_of::<Head>();
| ---------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
| |
| attempt to subtract with overflow
|
= note: `#[deny(const_err)]` on by default
error: any use of this value will cause an error
--> src/main.rs:15:28
|
15 | const CAPACITY:usize = Self::PAYLOAD_SIZE / mem::size_of::<Rec>();
| -----------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
| |
| referenced constant has errors
error: aborting due to 2 previous errors
error: could not compile `playground`.
To learn more, run the command again with --verbose.