小编stu*_*ffy的帖子

即使参数满足每个函数的约束,也不能调用函数的并集

我正在尝试编译此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)

typescript

7
推荐指数
1
解决办法
1454
查看次数

无法捕获 fn 项中的动态环境,但代码已经在 || 中 {} 闭包

我已将有问题的代码精简为以下示例:

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

6
推荐指数
1
解决办法
1918
查看次数

锈:借入的值必须在静态生命周期内有效

我正在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)

rust

4
推荐指数
1
解决办法
2189
查看次数

标签 统计

rust ×2

typescript ×1