gpt4 book ai didi

unit-testing - Rust 书籍单元测试示例导致死代码警告 - 为什么?

转载 作者:行者123 更新时间:2023-12-03 11:33:22 26 4
gpt4 key购买 nike

在学习 Rust 和尝试 Rust 书中的示例单元测试相关代码时:https://doc.rust-lang.org/book/ch11-01-writing-tests.html

我收到一条关于死代码的警告,该代码显然正在由单元测试执行。这是为什么?

lib.rs 中的代码

struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};

assert!(larger.can_hold(&smaller));
}
}

运行 cargo test 时的结果

$ cargo test
Compiling adder v0.1.0 (/Users/khorkrak/projects/rust/adder)
warning: associated function is never used: `can_hold`
--> src/lib.rs:8:8
|
8 | fn can_hold(&self, other: &Rectangle) -> bool {
| ^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted

Finished test [unoptimized + debuginfo] target(s) in 0.19s
Running target/debug/deps/adder-1082c4b063a8fbe6

running 1 test
test tests::larger_can_hold_smaller ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

$ rustc --version
rustc 1.50.0 (cb75ad5db 2021-02-10)

最佳答案

改变这个

struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}

这样可以使死代码警告消失。

pub struct Rectangle {
width: u32,
height: u32,
}

impl Rectangle {
pub fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}

测试的结构和方法都需要公开。

关于unit-testing - Rust 书籍单元测试示例导致死代码警告 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66425963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com