我有一段奇怪的代码:
#![allow(unused)]
fn f<'a>() {}
fn g<'a: 'a>() {}
fn main() {
// let pf = f::<'static> as fn(); // (7)
let pg = g::<'static> as fn(); // (8)
//print!("{}", pf == pg);
}
Run Code Online (Sandbox Code Playgroud)
第7行如果没有注释就不能编译(有下面的错误),但是第8行可以编译。
#![allow(unused)]
fn f<'a>() {}
fn g<'a: 'a>() {}
fn main() {
// let pf = f::<'static> as fn(); // (7)
let pg = g::<'static> as fn(); // (8)
//print!("{}", pf == pg);
}
Run Code Online (Sandbox Code Playgroud)
'a: 'a第4行是什么意思?
示例代码?
fn main() {
let a = [1, 2, 3, 4, 5];
reset(a);
}
fn reset(mut b: [u32; 5]) {
b[0] = 5;
}
Run Code Online (Sandbox Code Playgroud)
变量a是一个不可变数组,reset函数的参数b是一个可变数组;直觉上我需要修改a为可变数组才能调用该reset方法,但是编译器告诉我不需要这样做,这是为什么呢?
fn main() {
let mut a = [1, 2, 3, 4, 5];
reset(a);
}
fn reset(mut b: [u32; 5]) {
b[0] = 5;
}
Run Code Online (Sandbox Code Playgroud)
fn main() {
let a = [1, 2, 3, 4, 5];
reset(a);
}
fn reset(mut b: [u32; 5]) {
b[0] = …Run Code Online (Sandbox Code Playgroud) 在此代码,sref1并且sref2是的地址s,和地址是相同的.ref和之间有什么区别&?
fn main() {
let s = String::from("hello");
let sref1 = &s;
let ref sref2 = s;
println!("{:p}", sref1);
println!("{:p}", sref2);
f1(&s);
f2(s);
}
fn f1(_s: &String) {
println!("{:p}", _s);
}
fn f2(ref _s: String) {
println!("{:p}", _s);
}
Run Code Online (Sandbox Code Playgroud)
_sin f1和f2也是字符串的地址,f2将取得所有权,但打印f2的地址与打印的地址不同f1.为什么?
我无法调用Foo::new(words).split_first()以下代码
fn main() {
let words = "Sometimes think, the greatest sorrow than older";
/*
let foo = Foo::new(words);
let first = foo.split_first();
*/
let first = Foo::new(words).split_first();
println!("{}", first);
}
struct Foo<'a> {
part: &'a str,
}
impl<'a> Foo<'a> {
fn split_first(&'a self) -> &'a str {
self.part.split(',').next().expect("Could not find a ','")
}
fn new(s: &'a str) -> Self {
Foo { part: s }
}
}
Run Code Online (Sandbox Code Playgroud)
编译器会给我一个错误信息
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:8:17
| …Run Code Online (Sandbox Code Playgroud)