英文:
Is there a way for me to implicitly bind the members of a let/match operation?
问题
在下面的代码中,ThreeD 是一个枚举类型,可以是 Point 或 Vector。函数 cross 的目的是计算两个 Vector 的叉积,并在其中任何一个参数是 Point 时引发错误。
为了计算结果,我需要左操作数(lhs)和右操作数(rhs)的 x、y 和 z 分量。然而,目前的代码中,第二个模式匹配会隐藏第一个模式匹配中的 x、y 和 z 成员。
一种选择是在第一个 let 语句之后显式地将 x、y 和 z 成员分配给临时变量,但这种方法感觉非常笨拙。
pub fn cross(lhs: ThreeD, rhs: ThreeD) -> ThreeD {
if let Vector { x, y, z } = lhs {
let lhs_x = x; // 我不喜欢这种方法!
let lhs_y = y; //
let lhs_z = z; //
if let Vector { x, y, z } = rhs {
// 这里进行虚拟计算 - 我知道这是错误的 ;-)
Vector { x: lhs_x * x, y: lhs_y * y, z: lhs_z * z }
} else {
panic!("无法计算点与点的叉积")
}
} else {
panic!("无法计算点与点的叉积")
}
}
如果你有任何其他问题,请随时提出。
英文:
E.g. in the code below, ThreeD is an enum which can either be a Point or a Vector. The function cross is intended to calculate the cross product of two Vectors, and panic if either argument is a Point.
In order to calculate the result I need the x, y and z components of both the lhs and the rhs. As it stands however the second match will obscure the x,y and z members from the first match.
One option is to explicitly assign the x, y, and z members to temporary variables, immediately after the first let statement, but this feels horribly klunky.
pub fn cross(lhs: ThreeD, rhs: ThreeD) -> ThreeD {
if let Vector { x, y, z } = lhs {
let lhs_x = x; // I DON'T LIKE THIS APPROACH!
let lhs_y = y; //
let lhs_z = z; //
if let Vector { x, y, z } = rhs {
// dummy calc here - I know this is wrong ;-)
Vector { x: lhs_x * x, y: lhs_y * y, z: lhs_z * z }
} else {
panic!("Cannot calculate cross product with a point")
}
} else {
panic!("Cannot calculate cross product against a point")
}
}
答案1
得分: 3
你可以使用以下语法在模式内将其绑定到不同的名称:
if let Vector { x: lhs_x, y: lhs_y, z: lhs_z } = lhs {
英文:
You can bind to a different name within the pattern using this syntax:
if let Vector { x: lhs_x, y: lhs_y, z: lhs_z } = lhs {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论