我是朱莉娅的新手。这可能是一个愚蠢的问题,但我似乎无法正确理解此问题的语法。
我可以
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)
写这个的正确方法是什么?
谢谢
我正在阅读《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)