我正在阅读这本书,但我不明白为什么这个函数不能编译:
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines() // Fetch an iterator for each line in `contents`
.map(|x| x.to_lowercase()) // (x is now String) Convert each line to lowercase
.filter(|x| x.contains(query)) // Filter out lines that do not contain query
.map(|x| x.trim()) // Eliminate extra whitespace
.collect() // Consume iterator and produce Vec<&str>
}
Run Code Online (Sandbox Code Playgroud)
如果没有该to_lowercase()行,它将运行,我猜这是因为它将返回 aString而不是&str我们最后需要输出的。但是,当我将转换替换回&strlike 时:
// -- snip --
.map(|x| x.to_lowercase().to_str())
// …Run Code Online (Sandbox Code Playgroud) 我创建了一个新的子视图,其中包含其他视图的标题。它有一个箭头图标,我想将一个闭包传递给这个子视图(profileClose 是一个函数):
PlainHeader(title: getLocalizedText("edit profile"), action: profileClose)
Run Code Online (Sandbox Code Playgroud)
问题是我希望这个闭包是可选的。所以我决定将它包装起来,() ? = nil但在我每次使用时都这样做之后PlainHeader(...)。Xcode 说"Extra argument 'action' in call"
import SwiftUI
struct PlainHeader: View {
var title: String
let action: (() -> Void)? = nil
var body: some View {
VStack(spacing: 0) {
ZStack {
VStack(spacing: 0) {
HStack {
Image("arrow-back")
.resizable()
.scaledToFit()
.frame(width: 18, height: 7)
.padding(.leading, 31)
Spacer()
}
.onTapGesture {
print("[debugUI] action called")
if self.action != nil {
self.action!()
}
}
}
VStack {
HStack …Run Code Online (Sandbox Code Playgroud) 我是 Rust 新手,正在阅读官方书籍。我正在研究一个简单的 grep 示例,并希望创建一个exit可以在不同地方使用的函数。不幸的是,在闭包中使用此函数unwrap_or_else会导致编译错误。我不清楚为什么,因为当我直接在闭包中使用函数的内容时,它会起作用。
这是我的main.rs文件:
use std::env;
use std::fs;
use std::process;
use std::error::Error;
use std::fmt::Display;
struct Config{
query: String,
filename: String,
}
impl Config {
fn new(input: &[String]) -> Result<Config, &'static str> {
if input.len() < 3 {
return Err("Not enough arguments provided.");
}
let query = input[1].clone();
let filename = input[2].clone();
Ok(Config { query, filename })
}
}
fn run(cfg: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(&cfg.filename)?;
contents.find(&cfg.query).expect("Corrupted text …Run Code Online (Sandbox Code Playgroud) 请考虑以下示例(游乐场):
struct Animal<'a> {
format: &'a dyn Fn() -> (),
}
impl <'a>Animal<'a> {
pub fn set_formatter(&mut self, _fmt: &'a dyn Fn() -> ()) -> () {} // Getting rid of 'a here satisfies the compiler
pub fn bark(&self) {}
}
fn main() {
let mut dog: Animal = Animal { format: &|| {()} };
let x = 0;
dog.set_formatter(&|| {
println!("{}", x); // Commenting this out gets rid of the error. Why?
});
dog.bark(); // Commenting this …Run Code Online (Sandbox Code Playgroud) 我正在使用 Laravel 8 和 PHP 8。
我有一个在全局范围内定义并分配null值的变量。
我正在使用 laravel 的集合each函数来迭代每个元素。在这个闭包中,我有另一个闭包,它是集合的filter函数。我将过滤器的输出分配function给全局变量,它正在工作,但仅在函数闭包内each。(使用xdebug检查)
null即使我使用函数在闭包内传递了变量,但在闭包之外,变量use()又再次变为不工作。
$filtered = null;
$product->each(function ($price) use($coupons, $filtered) {
$filtered = $coupons->filter(function ($coupon) use($price) {
if (!empty($price->iso_code)) {
if ($coupon->iso_code = $price->iso_code) {
$a = $price->currency_code;
$b = $coupon->currency_code;
return $a == $b;
}
}
return $price->currency_code = $coupon->currency_code;
});
});
return $filtered; //null
Run Code Online (Sandbox Code Playgroud)
有人可以指导我如何将filter函数的输出分配给全局变量吗?
我在代码审查中被要求进行此更新。
从:
func bind(errorText: Driver<String>) {
errorText.drive(onNext: { [weak self] text in
self?.set(text: text)
self?.accessibilityValue = text
}).disposed(by: disposeBag)
}
Run Code Online (Sandbox Code Playgroud)
到:
func bind(errorText: Driver<String>) {
errorText.drive(onNext: { [weak self] text in
guard let self = self else { return }
self.set(text: text)
self.accessibilityValue = text
}).disposed(by: disposeBag)
}
Run Code Online (Sandbox Code Playgroud)
区别在于self?和 之间guard。
在第一个代码中,我的印象是self?当它调用的变量为零时被释放。或者是第二种方式,使用guard let self100% 确保self发布的方式?谢谢
有没有办法从用户提供的 Rust 中的 &str 类型获取函数指针。示例: use 提供了用户提供的函数名称我需要某种方式来调用该函数,最好是闭包或函数指针
我\xe2\x80\x99最近冒险进入了编写Scheme解释器的伟大领域,并且我\xe2\x80\x99遇到了一个障碍:闭包。据我了解,它们封装了一个本地环境,其中包含一个每次调用闭包时都会恢复的过程(这可能不完全正确)。我在网上任何地方都能找到的问题是如何正式定义闭包,即在 EBNF 语法中。我见过的大多数例子都说闭包是一个零参数的过程,它有一个嵌套在 let 表达式中的 lambda 表达式。这是定义Scheme闭包的唯一方法吗?更重要的是,如果\xe2\x80\x99s没有正式的方法来正式定义闭包,那么你实际上如何解释它?如果将所有 let 表达式转换为 lambda 会发生什么?例如,如果我这样声明一个闭包
\n(define (foo) (let ((y 0)) (\xce\xbb (x) (\xe2\x80\xa6))))\nRun Code Online (Sandbox Code Playgroud)\n然后将其赋值给一个变量
\n(define bar (foo))\nRun Code Online (Sandbox Code Playgroud)\n按什么顺序评估?从我\xe2\x80\x99所看到的,当foo声明时,它存储一个指向父环境的指针,并声明它自己的环境。如果我调用(bar),我应该立即替换到保存的本地环境中吗?
在处理各种参数获取和设置的网络处理程序中,我大量使用闭包。我有一个子例程,它接收一个闭包,并使用返回时作为参数传递的闭包构建另一个闭包(听起来很复杂,但这就是我想要这样的原因)。现在我有一个情况,我必须传递两个非常相似的闭包,每个闭包使用相同的对象方法,但具有不同的参数(对象方法检查传递的参数数量)。
我的想法是不传递两个(或更多)类似的闭包,而是传递$meth_ref对对象方法的引用(该对象也传递给返回闭包的函数),以便函数可以使用代码引用来传递不同的参数。
不幸的是我没有找到这样做的语法。
代码草图:
sub closure_maker($$)
{
my ($obj, $meth_ref) = @_;
return sub (...) {
$meth_ref->($obj);
...
$meth_ref->($obj, ...);
};
}
my @handlers = (closure_maker($obj1, ???), closure_maker($obj2, ???));
Run Code Online (Sandbox Code Playgroud)
我希望你能明白。
我正在通过Make a Lisp来学习 Rust。
\n作为评估器步骤的一部分,我需要创建一个将字符串(或其他内容)映射到函数的关联结构。在我更熟悉的语言(Ruby、Clojure)中,我会简单地在哈希图中定义匿名函数,例如
\n{ :+ (fn [a b] (+ a b))\n :- (fn [a b] (- a b)) } ; etc\nRun Code Online (Sandbox Code Playgroud)\n在 Rust 中,由于类型错误,这是不可能的expected closure, found a different closure。
let repl_env = HashMap::new();\n\nrepl_env.insert("+", |a, b| a + b);\nrepl_env.insert("-", |a, b| a - b); // expected closure, found a different closure\nRun Code Online (Sandbox Code Playgroud)\n我想这里发生的事情是
\nHashMap编译器正在推断as中的类型<String, WhateverTypeTheFirstClosureIs>no two closures, even if identical, have the …