// 定义返回的结构体
struct OutputStruct<'a, 'b, 'c> {
data1: &'a str,
data2: &'b i32,
data3: &'c f64,
}
// 复杂函数
fn complex_function<'a, 'b, 'c>(
ref1: &'a str,
ref2: &'b i32,
ref3: &'c f64,
) -> OutputStruct<'a, 'b, 'c> {
OutputStruct {
data1: ref1,
data2: ref2,
data3: ref3,
}
}
// 单线程测试
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_complex_function() {
let s = "hello";
let num = 42;
let f = 3.14;
let result = complex_function(s, &num, &f);
assert_eq!(result.data1, s);
assert_eq!(*result.data2, num);
assert_eq!(*result.data3, f);
}
}
// 多线程测试
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let s = Arc::new(Mutex::new(String::from("hello")));
let num = Arc::new(Mutex::new(42));
let f = Arc::new(Mutex::new(3.14));
let s_clone = s.clone();
let num_clone = num.clone();
let f_clone = f.clone();
let handle = thread::spawn(move || {
let s = s_clone.lock().unwrap();
let num = num_clone.lock().unwrap();
let f = f_clone.lock().unwrap();
let result = complex_function(&s, &num, &f);
assert_eq!(result.data1, &s);
assert_eq!(*result.data2, *num);
assert_eq!(*result.data3, *f);
});
handle.join().unwrap();
}
- 定义返回结构体
OutputStruct
:它包含三个不同生命周期参数的引用。
complex_function
函数:接受三个不同生命周期的引用作为参数,并返回OutputStruct
。
- 单线程测试
test_complex_function
:创建一些本地变量,并调用complex_function
,然后进行断言验证。
- 多线程测试:使用
Arc
和Mutex
来确保数据在多线程环境下的安全访问。创建线程,在线程内部调用complex_function
并进行断言验证。