Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
This article was originally published on Medium
Follow me:
Method and Associated Functions
Methods are defined within the context of a struct and their first parameter is always
self, which represents the instance of the struct the method is being called on. - The Rust Programming Language
Associated functions don’t take self as a parameter and they are not methods because they don’t have an instance of the struct to work with.
A good example is String::from function.
We use the :: syntax with the struct name to call this associated function whereas we use . when we call a method.
A common associated function is a new function that returns a value of the type the associated function is associated with.
Final code
Line 7–11: We create a mutable variable ans with the type of i32 . Using for loop, we iterate &self.nums using ans ^=n.
We adjust the above code to the LeetCode environment.
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
let mut ans: i32 = 0;
for n in nums {
ans ^= n;
}
ans
}
}