dario3004
dario3004

Reputation: 21

invoke method implemented to a struct after declared in main

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

Answers (1)

tenshi
tenshi

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 of rectangle: &Rectangle. The &self is actually short for self: &Self. Within an impl block, the type Self is an alias for the type that the impl block is for. Methods must have a parameter named self of type Self for their first parameter, so Rust lets you abbreviate this with only the name self in the first parameter spot.

Playground

Upvotes: 3

Related Questions