面试题答案
一键面试- 基本思路:
- 使用可动态增长和收缩的数据结构来存储这些参数。
- 提供方法来添加和移除参数。
- 数据结构:
Vec<T>
是一个不错的选择,它是Rust标准库中提供的动态数组。可以在运行时动态地添加和移除元素。例如,如果参数是i32
类型,可以使用Vec<i32>
。- 如果参数类型不同,可以考虑使用
Vec<Box<dyn Trait>>
,其中Trait
是所有参数类型都实现的某个 trait。例如,如果所有参数类型都实现了Debug
trait,可以定义为Vec<Box<dyn Debug>>
。
- 语法:
- 函数定义:
fn variable_args(mut args: Vec<i32>) { // 添加参数 args.push(5); // 移除参数 if let Some(removed) = args.pop() { println!("Removed: {}", removed); } // 处理参数 for arg in args.iter() { println!("Arg: {}", arg); } }
- 调用函数:
fn main() { let mut initial_args = vec![1, 2, 3]; variable_args(initial_args); }
- 如果参数类型不同,结合 trait 对象的示例如下:
trait Printable { fn print(&self); } struct A { value: i32 } struct B { value: String } impl Printable for A { fn print(&self) { println!("A: {}", self.value); } } impl Printable for B { fn print(&self) { println!("B: {}", self.value); } } fn variable_different_args(mut args: Vec<Box<dyn Printable>>) { let new_a = Box::new(A { value: 10 }); args.push(new_a); if let Some(removed) = args.pop() { removed.print(); } for arg in args.iter() { arg.print(); } } fn main() { let mut initial_args = vec![ Box::new(A { value: 1 }), Box::new(B { value: "hello".to_string() }) ]; variable_different_args(initial_args); }
- 函数定义: