Skip to content

ch13-01 use of value as method and field name #1740

@davidnx

Description

@davidnx

In listing 13-10, value is used as a field in struct Cacher<T> but value is also used as a method name in impl<T> Cacher<T>.

An explanation of why this is acceptable, and when it is or isn't a good idea, would be helpful.

Listing 13-9:

struct Cacher<T>
    where T: Fn(u32) -> u32
{
    calculation: T,
    value: Option<u32>, // DEFINED HERE
}

Listing 13-10:

impl<T> Cacher<T>
    where T: Fn(u32) -> u32
{
    fn new(calculation: T) -> Cacher<T> {
        Cacher {
            calculation,
            value: None,
        }
    }

    fn value(&mut self, arg: u32) -> u32 { // DEFINED HERE
        match self.value {
            Some(v) => v,
            None => {
                let v = (self.calculation)(arg);
                self.value = Some(v);
                v
            },
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions