函数指针实现所有三个闭包特征(
Fn,FnMut和FnOnce),因此您总是可以将函数指针作为期望闭包的函数的参数传递.最好使用泛型类型和闭包特征之一来编写函数,这样您的函数就可以接受函数或闭包.
将闭包传递给接受函数指针作为参数的函数不会编译:
fn main() {
let a = String::from("abc");
let x = || println!("{}", a);
fn wrap(c: fn() -> ()) -> () {
c()
}
wrap(x);
}
Run Code Online (Sandbox Code Playgroud)
error[E0308]: mismatched types
--> src/main.rs:10:10
|
10 | wrap(x);
| ^ expected fn pointer, found closure
|
= note: expected type `fn()`
found type `[closure@src/main.rs:4:13: 4:33 a:_]`
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
我删除了它的工作目录,因为这个git工作树不再有用了,然后我git branch -D pubsub-sketch-tree在主存储库的目录下.抛出的错误:
error: Cannot delete branch 'pubsub-sketch-tree' checked out at '/Users/zhouhancheng/??/github_own/sketch_worktree/pubsub-sketch_tree'
Run Code Online (Sandbox Code Playgroud)
但是'/ Users/zhouhancheng /编程/ github_own/sketch_worktree/pubsub-sketch_tree'已被删除.
我从byteorder读取了以下语法:
rdr.read_u16::<BigEndian>()
Run Code Online (Sandbox Code Playgroud)
我找不到任何解释语法的文档 instance.method::<SomeThing>()
function A这需要function B作为参数,再function B取function C作为参数.我尝试下面的语法,但这给了我一个错误:
fn a(b: impl Fn(impl Fn() -> ()) -> ()) -> () {
// ...
}
Run Code Online (Sandbox Code Playgroud)
error[E0666]: nested `impl Trait` is not allowed
--> src/main.rs:2:21
|
2 | fn a(b: impl Fn(impl Fn() -> ()) -> ()) -> () {
| --------^^^^^^^^^^^^^^^-------
| | |
| | nested `impl Trait` here
| outer `impl Trait`
Run Code Online (Sandbox Code Playgroud)
出于某种原因,我不能使用&dyn关键字:
fn a(b: impl Fn(&dyn Fn() -> ()) -> ()) -> () …Run Code Online (Sandbox Code Playgroud) 此代码段不会编译,因为struct A实例比s2其在其字段中保存的引用更长s.没问题.
struct A<'a> {
s: &'a usize,
}
let s1 = 100;
let mut a = A { s: &s1 };
{
let s2 = 1000;
a.s = &s2;
}
Run Code Online (Sandbox Code Playgroud)
在字符串文字的相同情况下,它编译.为什么?
struct A<'a> {
s: &'a str,
}
let s1 = "abc";
let mut a = A { s: &s1 };
{
let s2 = "abcd";
a.s = &s2;
}
Run Code Online (Sandbox Code Playgroud)