为什么Rust有String和str?String和之间有什么区别str?什么时候使用String而不是str反之亦然?其中一个被弃用了吗?
据我所知,引用/指针别名会阻碍编译器生成优化代码的能力,因为它们必须确保在两个引用/指针确实是别名的情况下,生成的二进制文件的行为正确。例如,在以下C代码中,
void adds(int *a, int *b) {
*a += *b;
*a += *b;
}
Run Code Online (Sandbox Code Playgroud)
当clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)用-O3标志编译时,它发出
0000000000000000 <adds>:
0: 8b 07 mov (%rdi),%eax
2: 03 06 add (%rsi),%eax
4: 89 07 mov %eax,(%rdi) # The first time
6: 03 06 add (%rsi),%eax
8: 89 07 mov %eax,(%rdi) # The second time
a: c3 retq
Run Code Online (Sandbox Code Playgroud)
下面的代码存回(%rdi)两次的情况下,int *a和int *b别名。
当我们明确告诉编译器这两个指针不能使用restrict关键字别名时:
void adds(int * restrict a, int * restrict …Run Code Online (Sandbox Code Playgroud) 我已经实现了以下方法和单元测试:
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
fn read_file(path: &Path) {
let mut file = File::open(path).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
println!("{}", contents);
}
#[test]
fn test_read_file() {
let path = &Path::new("/etc/hosts");
println!("{:?}", path);
read_file(path);
}
Run Code Online (Sandbox Code Playgroud)
我以这种方式运行单元测试:
rustc --test app.rs; ./app
Run Code Online (Sandbox Code Playgroud)
我也可以运行它
cargo test
Run Code Online (Sandbox Code Playgroud)
我收到一条消息说测试已通过,但println!屏幕上从未显示过.为什么不?
当在Rust中的一个数组上运行求和循环时,我发现CAPACITY> = 240 时性能会大幅下降。CAPACITY= 239的速度大约是80倍。
Rust对“短”数组进行了特殊的编译优化吗?
与编译rustc -C opt-level=3。
use std::time::Instant;
const CAPACITY: usize = 240;
const IN_LOOPS: usize = 500000;
fn main() {
let mut arr = [0; CAPACITY];
for i in 0..CAPACITY {
arr[i] = i;
}
let mut sum = 0;
let now = Instant::now();
for _ in 0..IN_LOOPS {
let mut s = 0;
for i in 0..arr.len() {
s += arr[i];
}
sum += s;
}
println!("sum:{} time:{:?}", sum, …Run Code Online (Sandbox Code Playgroud) 我有以下内容:
let mut my_number = 32.90;
Run Code Online (Sandbox Code Playgroud)
我该如何打印my_number?
使用type并type_of没有奏效.还有其他方法可以打印数字的类型吗?
我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:
struct Thing {
count: u32,
}
struct Combined<'a>(Thing, &'a u32);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing { count: 42 };
Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)
有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:
struct Combined<'a>(Thing, &'a Thing);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing::new();
Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)
有时,我甚至没有参考该值,我得到同样的错误:
struct Combined<'a>(Parent, Child<'a>);
fn make_combined<'a>() -> Combined<'a> {
let parent = Parent::new();
let child = parent.child();
Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)
在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?
我正在阅读Rust书的生命周章,我在这个例子中看到了命名/显式生命周期:
struct Foo<'a> {
x: &'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!("{}", x); // |
} // -+ x goes out …Run Code Online (Sandbox Code Playgroud) struct SemanticDirection;
fn main() {}
Run Code Online (Sandbox Code Playgroud)
warning: struct is never used: `SemanticDirection`
--> src/main.rs:1:1
|
1 | struct SemanticDirection;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(dead_code)] on by default
Run Code Online (Sandbox Code Playgroud)
我会将这些警告重新发送给任何严肃的事情,但我只是在修补这种语言而这正在驱使我蝙蝠.
我尝试添加#[allow(dead_code)]到我的代码,但这不起作用.
我正在试图弄清楚如何匹配StringRust.
我最初尝试过像这样的匹配,但我发现Rust不能暗中强制转换std::string::String为&str.
fn main() {
let stringthing = String::from("c");
match stringthing {
"a" => println!("0"),
"b" => println!("1"),
"c" => println!("2"),
}
}
Run Code Online (Sandbox Code Playgroud)
这有错误:
error[E0308]: mismatched types
--> src/main.rs:4:9
|
4 | "a" => println!("0"),
| ^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
Run Code Online (Sandbox Code Playgroud)
然后我尝试构造新String对象,因为我找不到将a String转换为a的函数&str.
fn main() {
let stringthing = String::from("c");
match stringthing {
String::from("a") => println!("0"),
String::from("b") => …Run Code Online (Sandbox Code Playgroud) 我正在学习/试验Rust,在我用这种语言找到的所有优雅中,有一个让我感到困惑并且看起来完全不合适的特点.
在进行方法调用时,Rust会自动取消引用指针.我做了一些测试来确定确切的行为:
struct X { val: i32 }
impl std::ops::Deref for X {
type Target = i32;
fn deref(&self) -> &i32 { &self.val }
}
trait M { fn m(self); }
impl M for i32 { fn m(self) { println!("i32::m()"); } }
impl M for X { fn m(self) { println!("X::m()"); } }
impl M for &X { fn m(self) { println!("&X::m()"); } }
impl M for &&X { fn m(self) { println!("&&X::m()"); } }
impl M for &&&X { …Run Code Online (Sandbox Code Playgroud) rust ×10
lifetime ×2
llvm-codegen ×2
reference ×2
string ×2
arrays ×1
dead-code ×1
dereference ×1
match ×1
performance ×1
println ×1
types ×1
warnings ×1