Reputation: 21
I'm new to rust so I'm not experienced with the way its object-oriented feature functions, I've followed a page but have countered in this situation where I cannot invoke ciao() from the instance of vec but instead, I have to specify by using Vet3::.. but I did assign to vec the type of struct of vet3 so shouldn't it inherit the methods? and if not how to do it in rust, thanks for your patience
pub struct Vet3<T>{
x: T,
y: T,
z: T
}
impl<T> Vet3<T>{
pub fn new(x: T, y: T, z: T) -> Self {
Self { x,y,z }
}
pub fn ciao(){
print!("hello world");
}
}
fn main(){
//let mut sc = ScannerAscii::new(io::stdin());
let vect : Vet3<i64>;
vect = Vet3::new(1, 2, 3);
Vet3::<i64>::ciao();
}
Upvotes: 0
Views: 47
Reputation: 26404
"Instance" methods need to take a self
in some way:
impl<T> Vet3<T>{
pub fn new(x: T, y: T, z: T) -> Self {
Self { x,y,z }
}
pub fn ciao(&self) { // take a reference to self
print!("hello world");
}
}
Your new
method is "static" since it doesn't have a self
parameter. From The Book:
In the signature for
area
, we use&self
instead ofrectangle: &Rectangle
. The&self
is actually short forself: &Self
. Within animpl
block, the typeSelf
is an alias for the type that theimpl
block is for. Methods must have a parameter namedself
of typeSelf
for their first parameter, so Rust lets you abbreviate this with only the nameself
in the first parameter spot.
Upvotes: 3