我正在尝试编译此Typescript代码段:
function foo(v: string) { return 'foo'; }
function bar(v: string | number) { return 'bar'; }
const notCallable: typeof foo | typeof bar = function() {} as any;
// Fails type check, even though all the unioned functions accept string.
notCallable('a');
Run Code Online (Sandbox Code Playgroud)
编译器推断notCallableas 的类型((v: string) => string) | ((v: string | number) => string),看起来不错,但不被视为可调用:
无法调用类型缺少调用签名的表达式。输入'(((v:string)=> string)| (((v:字符串|数字)=>字符串)'没有兼容的呼叫签名。
请注意,如果参数列表匹配,则即使返回类型不同,它也可以正常工作。
function foo(v: string) { return 'foo'; }
function bar(v: string) { return 0; }
const callable: typeof foo …Run Code Online (Sandbox Code Playgroud) 我已将有问题的代码精简为以下示例:
fn foo(input_vector: Vec<()>) {
const bar: Option<()> = []
.iter()
.map(|_| { input_vector; })
.nth(0);
}
fn main() {
foo(vec![]);
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误:
fn foo(input_vector: Vec<()>) {
const bar: Option<()> = []
.iter()
.map(|_| { input_vector; })
.nth(0);
}
fn main() {
foo(vec![]);
}
Run Code Online (Sandbox Code Playgroud)
如果我已经使用了闭包,为什么编译器告诉我使用闭包?
我正在Rust的一个玩具射线追踪器项目中工作,并且挂了一个与生命有关的错误。我将代码简化为以下独立的失败案例:
struct Material {}
pub struct Sphere<'a> {
material: &'a Material,
}
pub trait AnySceneObject {}
impl<'a> AnySceneObject for Sphere<'a> {}
pub struct Scene {
objects: Vec<Box<AnySceneObject>>,
}
fn main() {
let material = Material {};
let boxed_sphere: Box<AnySceneObject> = Box::new(Sphere { material: &material });
Scene { objects: vec![boxed_sphere] };
}
Run Code Online (Sandbox Code Playgroud)
哪个抱怨
error[E0597]: `material` does not live long enough
--> main.rs:17:74
|
17 | let boxed_sphere: Box<AnySceneObject> = Box::new(Sphere { material: &material });
| ^^^^^^^^ does not live long enough …Run Code Online (Sandbox Code Playgroud)