小编Car*_*cho的帖子

Julia 语法 - 带有 where 子句的函数的返回类型注释

我是朱莉娅的新手。这可能是一个愚蠢的问题,但我似乎无法正确理解此问题的语法。

我可以

check_condition(func::F, arg::Int) where {F} = func(arg)
Run Code Online (Sandbox Code Playgroud)

check_condition(func::Function, arg::Int)::Bool = func(arg)
Run Code Online (Sandbox Code Playgroud)

但是如果我想同时包含类型注释和外部 where 子句,我会不断收到语法错误。以下似乎不起作用:

check_condition(func::F, arg::Int) where {F}::Bool = func(arg)
(check_condition(func::F, arg::Int) where {F})::Bool = func(arg)
check_condition(func::F, arg::Int)::Bool where {F} = func(arg)
check_condition::Bool(func::F, arg::Int) where {F} = func(arg)
Run Code Online (Sandbox Code Playgroud)

这确实有效,但我相信它不等于我想要的,因为类型参数从方法体中隐藏(假设我想在某个地方使用它)

check_condition(func::F where {F}, arg::Int)::Bool = func(arg)
Run Code Online (Sandbox Code Playgroud)

写这个的正确方法是什么?

谢谢

julia

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

引用以及移动与复制

我正在阅读《Rust》一书的第 4 章,我有 Python 背景。

让我有点困惑的是这不能编译:

fn do_something(s3: String) {
    println!("{}", s3);
}

fn main() {
    let s = String::from("Hello");
    do_something(s);
    println!("{}", s);
}
Run Code Online (Sandbox Code Playgroud)

(因为它不应该,因为 s 在函数调用中被移动),但是这样做:

fn do_something(s3: &String) {
    println!("{}", s3);
}

fn main() {
    let s1 = String::from("Hello");
    let s2 = &s1;
    do_something(s2);
    println!("{}", s2);
}
Run Code Online (Sandbox Code Playgroud)

如果我理解正确的话,这是因为 s1 已经是一个指针,所以 s2 是一个指向(堆栈分配的)指针的指针(好吧,是一个引用)。因此,s2在函数调用中被复制而不是被移动。是这样吗?上面的和这个一样吗?

fn main() {
    let a = 5;
    let b = &a;
    do_something(b);
    println!("{}", b);
}
Run Code Online (Sandbox Code Playgroud)

ownership rust

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

标签 统计

julia ×1

ownership ×1

rust ×1