如下代码所示,我想封装一个定时函数,返回一个闭包的结果和执行时间。
use tap::prelude::Pipe;
use std::time::{Instant, Duration};
pub fn measure_time_with_value<T>(f: impl FnOnce() -> T) -> (T, Duration) {
Instant::now().pipe(|s| (f(), s)).pipe(|(f, s)| (f, s.elapsed()))
}
Run Code Online (Sandbox Code Playgroud)
但是不知道tuple参数的执行顺序是不是从左到右,即是否可以简化为如下代码:
pub fn measure_time_with_value<T>(f: impl FnOnce() -> T) -> (T, Duration) {
Instant::now().pipe(|s| (f(), s.elapsed()))
}
Run Code Online (Sandbox Code Playgroud) 变量和函数具有相同的名称。如何调用函数?
fn main() {
let a = 1;
fn a() -> i32 {
2
}
println!("{}", a());
}
Run Code Online (Sandbox Code Playgroud)
Rust 编译器告诉我:
error[E0618]: expected function, found `{integer}`
Run Code Online (Sandbox Code Playgroud)
换句话说,Rust 编译器不会调用a函数,而是访问a变量。
此功能即将推出Kotlin 1.4。这是摘录自KotlinConf'19.
fun interface Action {
fun run()
}
fun runAction(a: Action) = a.run()
runAction{
println("Hello")
}
Run Code Online (Sandbox Code Playgroud)
看起来不错,但我仍然不知道它有什么作用。
什么是函数接口?它的实用价值是什么?它可以用于哪些具体场景?
实现 Kotlin 标准库扩展函数let:
extension KtStd<T, R> on T {
R let(R f(T it)) => f(this);
}
Run Code Online (Sandbox Code Playgroud)
并编写一个 CLI sum 计算器(问题不能简化),期望:
input: 1 2 3 4 5 6 7 8 9
output: 45
input: apple 1.2 banana 3.4
output: 4.6
Run Code Online (Sandbox Code Playgroud)
然后代码:
main() {
stdin.readLineSync(encoding: Encoding.getByName('utf-8')).split(" ")
.map((s) => double.tryParse(s)).where((e) => e != null).fold(0, (acc, i) => acc + i)
.let((d) => d % 1 == 0 ? d.toInt() : d)
.let((it) => print(it));
}
Run Code Online (Sandbox Code Playgroud)
输入时1 2 3,得到错误信息: …
一个简单的例子generic parameters of trait function:
trait Ext: Sized {
fn then<R>(self, f: fn(Self) -> R) -> R {
f(self)
}
}
impl<T> Ext for T {}
Run Code Online (Sandbox Code Playgroud)
一个简单的例子generic parameters of trait:
trait Ext<R>: Sized {
fn then(self, f: fn(Self) -> R) -> R {
f(self)
}
}
impl<T, R> Ext<R> for T {}
Run Code Online (Sandbox Code Playgroud)
两者有什么区别?
什么时候应该使用“特征函数的通用参数”,什么时候应该使用“特征的通用参数”?
货物.toml:
[features]
parallel = ["rayon"]
[dependencies.rayon]
version = "1.5"
optional = true
Run Code Online (Sandbox Code Playgroud)
库.rs:
#[cfg(feature = "parallel")]
pub mod par;
Run Code Online (Sandbox Code Playgroud)
锈迹分析仪:
code is inactive due to #[cfg] directives: feature = "parallel" is disabled
Run Code Online (Sandbox Code Playgroud)
如何启用可选依赖项?