#[derive(Debug)]
pub struct Point {
x: f64,
y: f64
}
impl Point {
pub fn new(x: f64, y: f64) -> Point {
Point {
x, y
}
}
pub fn dest(&self, other: &Point) -> f64 {
// How could it work? Why does it can accessing the private field?
((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
// --------^^^^^^^----------------------^^^^^^^
}
}
mod tests {
use super::Point;
#[test]
fn it_works() {
let a = Point::new(0., 0.);
let b = Point::new(3., 4.);
assert_eq!(5., a.dest(&b));
assert_eq!(5., b.dest(&a));
}
}
Private fields can only be accessed within the module the type is defined. So you can access the field x
of the struct Point
within this module.
Thanks a lot, I understand now.
Playground
pub mod point {
#[derive(Debug)]
pub struct Point {
x: f64,
y: f64
}
impl Point {
pub fn new(x: f64, y: f64) -> Point {
Point {
x, y
}
}
pub fn dest(&self, other: &Point) -> f64 {
((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
}
}
#[derive(Debug)]
pub struct AnotherLine {
start: Point,
end: Point,
}
impl AnotherLine {
pub fn new(start: Point, end: Point) -> Self {
Self {
start, end
}
}
pub fn length_v1(&self) -> f64 {
((self.start.x - self.end.x).powi(2) + (self.start.y - self.end.y).powi(2)).sqrt()
}
pub fn length_v2(&self) -> f64 {
self.start.dest(&self.end)
}
}
}
pub mod line {
use super::point::Point;
#[derive(Debug)]
pub struct Line {
start: Point,
end: Point,
}
impl Line {
pub fn new(start: Point, end: Point) -> Line {
Line {
start, end
}
}
/* could not compile
pub fn length_v1(&self) -> f64 {
((self.start.x - self.end.x).powi(2) + (self.start.y - self.end.y).powi(2)).sqrt()
}
*/
pub fn length(&self) -> f64 {
self.start.dest(&self.end)
}
}
}
mod tests {
use super::point::{AnotherLine, Point};
use super::line::Line;
#[test]
fn test_point_dest() {
let a = Point::new(0., 0.);
let b = Point::new(3., 4.);
assert_eq!(5., a.dest(&b));
assert_eq!(5., b.dest(&a));
}
#[test]
fn test_line_length() {
let a = Point::new(0., 0.);
let b = Point::new(3., 4.);
let l = Line::new(a, b);
assert_eq!(5., l.length());
}
#[test]
fn test_another_line_length() {
let a = Point::new(0., 0.);
let b = Point::new(3., 4.);
let l = AnotherLine::new(a, b);
assert_eq!(5., l.length_v1());
assert_eq!(5., l.length_v2());
}
}
By the way, where did you expect to be able to access private fields if not inside the own impl
of Point
? If you couldn't access them evem in the impl, what would be the point in private fields at all? They would be completely unusable.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.