Rust调用Vector::new不能指定参数名?编译报错问题咨询
Rust函数调用无法使用参数名传参的原因
我用Rust实现一个摆(Pendulum)结构,同时自定义了Vector结构体。调用vector::Vector::new(x: 0.0, y: 0.0)时编译器报错,但直接传vector::Vector::new(0.0, 0.0)就能正常运行,想搞懂为啥不能用参数名传递参数。
相关代码
fn main() { println!("Hello, world!"); } struct Pendulum { origin: vector::Vector, position: vector::Vector, angle: f32, angular_velocity: f32, angular_acceleration: f32, r: f32, // 摆长 m: f32, // 质量 g: f32, // 重力加速度 } impl Pendulum { fn new(x: f32, y: f32, r: f32) -> Pendulum { Pendulum { origin: vector::Vector::new(x, y), position: vector::Vector::new(x: 0.0, y: 0.0), // 这里报错 angle: 1.0, angular_velocity: 0.0, angular_acceleration: 0.0, r: r, m: 1.0, g: 1.5, } } fn update() {} fn draw() {} } mod vector { pub struct Vector { pub x: f32, pub y: f32, } impl Vector { pub fn new(x: f32, y: f32) -> Vector { Vector { x, y } } pub fn add(&mut self, other: Vector) -> &Vector { self.x += other.x; self.y += other.y; self } pub fn set(&mut self, x: f32, y: f32) { self.x = x; self.y = y; } } }
编译器错误信息
error: invalid `struct` delimiters or `fn` call arguments src/main.rs:24:23 > | 24 | position: vector::Vector::new(x: 0.0, y: 0.0), > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > | help: if `vector::Vector::new` is a struct, use braces as delimiters > | 24 | position: vector::Vector::new { x: 0.0, y: 0.0 }, > | ~ ~ help: if `vector::Vector::new` is a function, use the arguments directly > | 24 - position: vector::Vector::new(x: 0.0, y: 0.0), 24 + position: vector::Vector::new(0.0, 0.0), > | error: could not compile `rust-pendulum` due to previous error
问题原因与解决办法
Rust不支持普通函数调用时使用参数名传参,你写的x: 0.0这种键值对语法,只有两种合法场景:
- 结构体实例化(比如
Vector { x: 0.0, y: 0.0 }) - 部分支持命名参数的宏调用(比如
dbg!)
而你的vector::Vector::new是一个普通的关联函数,不属于上述场景,因此必须严格按参数定义的顺序传递值,不能加参数名。
如果想要提升代码可读性,替代方案有两种:
- 先把参数赋值给带有语义的变量,再传递:
impl Pendulum { fn new(x: f32, y: f32, r: f32) -> Pendulum { let pos_x = 0.0; let pos_y = 0.0; Pendulum { origin: vector::Vector::new(x, y), position: vector::Vector::new(pos_x, pos_y), // ...其他字段 } } }
- 定义一个专门的参数结构体,让
new函数接收该结构体:
mod vector { pub struct Vector { pub x: f32, pub y: f32, } // 新增参数结构体 pub struct VectorInit { pub x: f32, pub y: f32, } impl Vector { pub fn new(params: VectorInit) -> Vector { Vector { x: params.x, y: params.y } } // ...其他方法 } } // 调用时就可以用命名参数形式 position: vector::Vector::new(vector::VectorInit { x: 0.0, y: 0.0 }),
最直接的解决方式是修改报错行,去掉参数名即可正常编译:
position: vector::Vector::new(0.0, 0.0),
内容的提问来源于stack exchange,提问作者Pacoco
相关产品推荐
相关产品推荐

