我创建了下面这两种方法来注销用户。当 logout2(...) 被调用时,用户可以在 logout1() 运行之前在 anyFinalChanges 中进行任何更改。
private func logout1() {
Cache.clearCache()
}
func logout2(anyFinalChanges: () -> (), userLoggedOut: () -> ()) {
anyFinalChangesInThisClosure()
logout()
userLoggedOut()
}
Run Code Online (Sandbox Code Playgroud)
当我实现注销方法时,第二个闭包不显示名称
.logOut2(anyFinalChanges: {
}) { //No Name here.. why is that?
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使闭包的名称始终出现?
我正在测试“并发请求”功能:
但我对如何动态创建闭包输入值感到困惑。
例如我有一个数组:
$a = [
'foo' => 'http//localhost/1',
'bar' => 'http//localhost/2'
];
Run Code Online (Sandbox Code Playgroud)
我需要动态地创建类似的东西:
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$responses = Http::pool(fn (Pool $pool) => [
$pool->as('foo')->get('http://localhost/1'),
$pool->as('bar')->get('http://localhost/2'),
]);
return $responses['foo']->body();
Run Code Online (Sandbox Code Playgroud)
更新$a关闭内容应该发生变化。我怎样才能做到这一点?
谢谢
我正在尝试创建一个方法,该方法采用 anOption<impl Fn() -> ()>作为参数,并且,如果此参数是Some(func),则存储func为闭包,但是,如果是None,则存储一些默认函数作为闭包。具体来说,我的代码如下:
fn foo()
{
println!("HI");
}
fn bar(baz: Option<impl Fn () -> ()>)
{
let func = match baz {
Some(func) => func,
//None => foo,
None => unimplemented!()
};
func();
}
pub fn main() {
bar(Some(foo));
}
Run Code Online (Sandbox Code Playgroud)
按原样,代码可以编译,这向我表明这foo确实应该与impl Fn () -> (). 但是,如果我用注释掉的手臂替换None我的手臂以设置为我的“默认实现”,我会收到以下错误:matchNonefoo
error[E0308]: `match` arms have incompatible types
--> <source>:10:17
|
6 | fn bar(baz: Option<impl Fn …Run Code Online (Sandbox Code Playgroud) 根据这个答案,Rust 将具有相同返回类型的异步块和闭包视为不同类型。
为什么 Rust 将具有相同签名的闭包视为不同类型?这是理论上的限制还是编译器的限制?
在 Haskell 中,它们受到相同的对待。
假设我有这个代码:
let mut s = "hi".to_string();
let c = || s.push_str(" yo");
c();
Run Code Online (Sandbox Code Playgroud)
它不会编译并生成此错误:
error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable
--> src\test.rs:120:9
|
119 | let c = || s.push_str(" yo");
| - - calling `c` requires mutable binding due to mutable borrow of `s`
| |
| help: consider changing this to be mutable: `mut c`
120 | c();
| ^ cannot borrow as mutable
For more information about this error, try …Run Code Online (Sandbox Code Playgroud) 我阅读了有关此主题的不同文章Eric Lippert 的博客和其他文章,并知道为什么这两个代码的工作方式不同
int[] values = { 7, 9, 13 };
List<Action> f = new List<Action>();
foreach (var value in values)
f.Add( () => Console.WriteLine("foreach value: " + value));
foreach (var item in f)
item();
f = new List<Action>();
for (int i = 0; i < values.Length; i++)
f.Add(() => Console.WriteLine("for value: " + ((i < values.Length) ? values[i] : i)));
foreach (var item in f)
item();
Run Code Online (Sandbox Code Playgroud)
但我没有找到明确的解释,为什么最终(从编译器 c# 版本 5 开始)决定“foreach 循环变量在逻辑上将位于循环体内部,因此闭包每次都会获得一个新的副本”。因为旧的实现提供了使用闭包 Lambda 的更多自由(“按值或按引用”),但要求程序员小心使用它,如果您需要 foreach …
我在理解闭包方面遇到了一些困难,所以我跳到一个论坛上询问一些有关幕后情况的问题。有人给我举了这样一个例子:
对于以下代码:
Run Code Online (Sandbox Code Playgroud)let x = String::new(); let f = || { println!("{x}") }; f();下面的代码是 Rust 在后台生成的(这只是一个近似值,它并没有真正运行):
Run Code Online (Sandbox Code Playgroud)struct UnnameableClosureType<'a> { x0: &'a String, } impl<'a> Fn<()> for UnnameableClosureType<'a> { type Output = (); extern "rust-call" fn call(&self, args: Args) -> Self::Output { println!("{}", self.x0); } } impl<'a> FnMut<()> for UnnameableClosureType<'a> { type Output = (); extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { self.call(args) } } impl<'a> FnOnce<()> for UnnameableClosureType<'a> { type Output = (); extern "rust-call" fn …
我如何使用闭包来实现这个???
addTogether(2)(3);
我还需要相同的函数来返回正常添加,因为addTogether(2,3)返回5.
斯威夫特3:
我有两个数组,一个数组是dictionary(json)的数组,另一个数组是索引Path(具有元素行和节的集合类型Index)的索引(Int值)。借助于第二个数组的索引行,我需要从第一个数组中删除元素。
var arrayString = [ // Array with Json elements
{ "name" : "A" },
{ "name" : "B" },
{ "name" : "C" },
{ "name" : "D" },
{ "name" : "E" },
{ "name" : "F" },
{ "name" : "G" },
{ "name" : "H" }
]
Run Code Online (Sandbox Code Playgroud)
现在第二个数组(将从第一个数组中删除)
var arrayIndex = [ 2, 3, 5 ] // Array with
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我想要像这样的结果数组
var arrayString = [
{ "name" : "A" },
{ "name" : "D" },
{ …Run Code Online (Sandbox Code Playgroud) 我尝试了这段代码
struct Bar {
public int Value;
}
async Task doItLater(Action fn) {
await Task.Delay(100);
fn();
}
void Main() {
Bar bar = new Bar { Value = 1 }; //Bar is a struct
doItLater(() => {
Console.WriteLine(bar.Value);
}).Wait();
}
Run Code Online (Sandbox Code Playgroud)
得到了输出1.现在这让我很困惑.我的逻辑如下
Task.Delay(100)命中时,该执行线程完成,并且请求TPL fn()稍后执行.bar 存储在堆栈上,当我们在闭包中访问它时,该帧不应该存在.那么我怎么得到一个输出1?