![](/img/trans.png)
[英]Do inner functions in JavaScript get hoisted? How do the scoping rules apply to them?
[英]Rust scoping rules for struct-owned functions
我试图了解impl
块中定义的函数的范围究竟是什么,但是不接受&self
作为参数。 例如,为什么下面的代码块不能编译? 我收到错误“无法在此范围内找到函数generate_a_result
”。
pub struct Blob {
num: u32,
}
impl Blob {
pub fn new() -> Blob {
generate_a_result()
}
fn generate_a_result() -> Blob {
let result = Blob {
num: 0
};
result
}
}
这些函数称为关联函数 。 它们位于该类型的命名空间中。 它们总是必须像Type::function()
一样被调用。 在你的情况下,那是Blob::generate_a_result()
。 但是,为了引用您自己的类型,有一个特殊的关键字Self
。 所以最好的解决方案是:
Self::generate_a_result()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.