gpt4 book ai didi

tuples - 玩转 Rust 的元组

转载 作者:行者123 更新时间:2023-11-29 08:08:12 25 4
gpt4 key购买 nike

这是玩 Rust 的链接:

http://rustbyexample.com/match/guard.html

我发现 Rust 在我对无符号变量取反时显示警告,因此执行下面的代码以

结尾

warning: negation of unsigned int variable may be unintentional

代码:

fn main() {
let some = 2953495866u;
let pair = (some, -some);
// TODO ^ Try different values for `pair`

println!("Tell me about {}", pair);
// Match can be used to destructure a tuple
match pair {
// Destructure the tuple
(x, y) if x == y => println!("These are twins"),
// The ^ `if condition` part is a guard
(x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
// `_` means don't bind the value to a variable
(x, _) if x % 2 == 1 => println!("The first one is odd"),
_ => println!("No correlation..."),
}
}

但是当你把代码改成有点像

let pair = (2953495866u, -2953495866);

它静默运行,以 (2953495866, 18446744070756055750) 的元组结束,这是 2 个无符号整数。至于我,我宁愿在这里收到有关将负数转换为 uint 的警告。

你怎么看待这种情况?

最佳答案

一个解释,以防万一。在这段代码中:

fn main() {
//let some = 2953495866u;
let pair = (2953495866u, -2953495866);
// TODO ^ Try different values for `pair`

println!("Tell me about {}", pair);
// Match can be used to destructure a tuple
match pair {
// Destructure the tuple
(x, y) if x == y => println!("These are twins"),
// The ^ `if condition` part is a guard
(x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
// `_` means don't bind the value to a variable
(x, _) if x % 2 == 1 => println!("The first one is odd"),
_ => println!("No correlation..."),
}
}

-2953495866 文字是无类型的;这意味着类型检查器可以从它的用法中推断出它的具体类型。事实证明,它被存储到一个元组中,然后这个元组被解构,并比较它的两个组成部分。因为第一个组件类型是uint(因为对应的字面量有u后缀),类型检查器判定第二个组件类型也是uint ,因此该文字也应该是 uint

未触发关于对无符号值求反的 lint 看起来确实像是编译器中的错误。我提交了here .

关于tuples - 玩转 Rust 的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25260919/

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