A module groups related Rust declarations and organizes a crate’s source code. Modules can live in files, directories, or nested inline definitions. section 5.5
Use these rules to structure a crate:
- Modules combine into crates, and a subdirectory under src/ becomes a module when it contains mod.rs. section 5.5
- Define modules inside a file with mod, and nest them to any depth. section 5.5
- Keep members private by default; use pub, pub(crate), pub(super), pub(in path), or pub(self) to control visibility. section 5.5
- Bring items into local scope with use. section 5.5
Testing inside a module
A Q7 implementation places its tests in a nested mod tests module. The tests use use super::* to access the surrounding implementation, then run with cargo test. section 5.5
Listing 5.14 Full code implementation of the Q7 format
#[derive(Debug,Clone,Copy,PartialEq,Eq)]
pub struct Q7(i8);
impl From<f64> for Q7 {
fn from (n: f64) -> Self {
if n >= 1.0 {
Q7(127)
} else if n <= -1.0 {
Q7(-128)
} else {
Q7((n * 128.0) as i8)
}
}
}
impl From<Q7> for f64 {
fn from(n: Q7) -> f64 {
(n.0 as f64) * 2f64.powf(-7.0)
}
}
impl From<f32> for Q7 {
fn from (n: f32) -> Self {
Q7::from(n as f64)
}
}
impl From<Q7> for f32 {
fn from(n: Q7) -> f32 {
f64::from(n) as f32
}
}
#[cfg(test)]
mod tests { #1
use super::*; #2
#[test]
fn out_of_bounds() {
assert_eq!(Q7::from(10.), Q7::from(1.));
assert_eq!(Q7::from(-10.), Q7::from(-1.));
}
#[test]
fn f32_to_q7() {
let n1: f32 = 0.7;
let q1 = Q7::from(n1);
let n2 = -0.4;
* let q2 = Q7::from(n2);
let n3 = 123.0;
let q3 = Q7::from(n3);
assert_eq!(q1, Q7(89));
assert_eq!(q2, Q7(-51));
assert_eq!(q3, Q7(127));
}
#[test]
fn q7_to_f32() {
let q1 = Q7::from(0.7);
let n1 = f32::from(q1);
assert_eq!(n1, 0.6953125);
let q2 = Q7::from(n1);
let n2 = f32::from(q2);
assert_eq!(n1, n2);
}
}
Inspect the Q7 implementation’s mod tests block and its use super::* import. section 5.5


































