我是Rust(1.31)的新手,我想了解一段不编译的简单代码:
fn main() {
s = String::from("foo");
match s {
"foo" => {
println!("Yes");
}
_ => {
println!("No");
}
}
}
Run Code Online (Sandbox Code Playgroud)
相关的错误是:
10 | "foo" => {
| ^^^^^ expected struct `std::string::String`, found reference
Run Code Online (Sandbox Code Playgroud)
发生此错误后,我决定将代码更改为:
fn main() {
let s = String::from("foo");
match s {
String::from("foo") => {
println!("Yes");
}
_ => {
println!("No");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样,我希望拥有正确的类型,但事实并非如此:
10 | String::from("foo") => {
| ^^^^^^^^^^^^^^^^^^^ not a tuple variant or struct
Run Code Online (Sandbox Code Playgroud)
我对编译器发出的消息感到非常困惑,最后我设法通过实现使其起作用:
fn main() {
let s = String::from("foo"); …Run Code Online (Sandbox Code Playgroud) 该值0.1不能表示为 64 位浮点数。精确值大致等于0.10000000000000000555
https://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
您可以使用以下简单的代码突出显示此行为:
timestep = 0.1
iterations = 1_000_000
total = 0
for _ in range(iterations):
total += timestep
print(total - timestep * iterations) # output is not zero but 1.3328826753422618e-06
Run Code Online (Sandbox Code Playgroud)
我完全理解为什么0.1不能表示为 float 64 的精确值,但我不明白的是为什么当我这样做时print(0.1),它输出0.1而不是作为 float 64 的基础值。
当然,基础值在以 10 为基数的系统上有更多的数字,因此应该涉及一些舍入,但我正在寻找所有值的规范以及如何控制它。
我遇到了一些应用程序在数据库中存储数据的问题:
str(0.1))会显示0.10.10000000000000000555,这会让最终用户感到困惑PS:我对其他价值观有其他问题
问候,