Understanding the parameter "I" in the context of the implementation of signs

When implementing a feature, we often use a keyword self, the pattern is as follows. I want to understand the many uses selfin this code example.

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

trait HasArea {
    fn area(&self) -> f64;          // first self: &self is equivalent to &HasArea
}

impl HasArea for Circle {
    fn area(&self) -> f64 {         //second self: &self is equivalent to &Circle
        std::f64::consts::PI * (self.radius * self.radius) // third:self
    }
}

My understanding:

  • First self: &selfequivalent &HasArea.
  • Second self: &selfequivalent &Circle.
  • The third selfrepresents Circle? If so, if self.radiusused twice, will this cause a movement problem?

In addition, a large number of examples showing the different uses of the keyword selfin a changing context would be greatly appreciated.

+4
2

.

, , , self :

impl S {
    fn foo(self) {}      // equivalent to fn foo(self: S)
    fn foo(&self) {}     // equivalent to fn foo(self: &S)
    fn foo(&mut self) {} // equivalent to fn foo(self: &mut S)
}

, self - , (, elision), .

:

impl HasArea for Circle {
    fn area(&self) -> f64 {   // like fn area(self: &Circle) -> ... 
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

self &Circle. , self.radius . radius Copy, , . , Copy, .

+5

.


, , : let () = ...;.

, 1- :

9 |         let () = self;
  |             ^^ expected &Self, found ()

:

16 |         let () = self;
   |             ^^ expected &Circle, found ()

, HasArea , .

, self? .

, , HasArea. , , , , , HasArea.

, . , :

trait HasArea: Debug {
    fn area(&self) -> f64;
}

Self: HasArea + Debug, , self HasArea Debug.


: , HasArea. Circle.

, self fn area(&self) &Circle.

, &Circle, , &Circle. ( ), .


.

, :

struct Segment(Point, Point);

impl Segment {
    fn length(&self) -> f64;
}

trait Segmentify {
    fn segmentify(&self) -> Vec<Segment>;
}

trait HasPerimeter {
    fn has_perimeter(&self) -> f64;
}

HasPerimeter , .

impl<T> HasPerimeter for T
    where T: Segmentify
{
    // Note: there is a "functional" implementation if you prefer
    fn has_perimeter(&self) -> f64 {
        let mut total = 0.0;
        for s in self.segmentify() { total += s.length(); }
        total
    }
}

self ? &T.

T? , Segmentify.

, T, , Segmentify HasPerimeter, ( println("{:?", self);, T Debug).

+4

Source: https://habr.com/ru/post/1659485/


All Articles