[英]How do I execute an implemented method in Rust?
I can't execute method which name is two_sum
implemented in a Solution impl.我无法执行在 Solution impl 中实现的名称为
two_sum
的方法。
I want to know how to execute two_sum
method from main
.我想知道如何从
main
执行two_sum
方法。
My source code is here.我的源代码在这里。
impl Solution {
pub fn two_sum(num: i32) -> i32 {
num + 1
}
}
fn main() {
let result = Solution::two_sum(1);
println!("{:?}", result);
}
Error message错误信息
failed to resolve: use of undeclared type Solution
use of undeclared type Solution
You need define what Solution
is and later implement two_sum.您需要定义什么是
Solution
,然后再实施 two_sum。 One way is you can define Solution
as an empty struct.一种方法是您可以将
Solution
定义为空结构。
struct Solution;
impl Solution {
pub fn two_sum(num: i32) -> i32 {
num + 1
}
}
fn main() {
let result = Solution::two_sum(1);
println!("{:?}", result);
}
Well, firstly, your two_sum
is an associated function, not a method.嗯,首先,你的
two_sum
是一个关联函数,而不是一个方法。 Secondly, it's associated with nothing - you didn't declare a type named Solution
(you needed to write struct Solution;
at least).其次,它没有任何关联——您没有声明名为
Solution
的类型(您至少需要编写struct Solution;
)。 Thirdly, you don't need to Debug
an i32
, so we'll replace {:?}
with {}
.第三,您不需要
Debug
i32
,所以我们将用 {} 替换{:?}
{}
。
struct Solution;
impl Solution {
pub fn two_sum(num: i32) -> i32 {
num + 1
}
}
fn main() {
let result = Solution::two_sum(1);
println!("{}", result);
}
Fourthly, creating a type just to write a function is a really bad practice.第四,创建一个类型只是为了编写一个函数是一种非常糟糕的做法。
So what are we gonna do?那我们要做什么?
fn two_sum(num: i32) -> i32 {
num + 1
}
fn main() {
let result = two_sum(1);
println!("{}", result);
}
That's it!而已! I don't know why did you call it
two_sum
tho.我不知道你为什么称它为
two_sum
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.