xref: /aosp_15_r20/external/bazelbuild-rules_rust/examples/hello_lib/src/greeter.rs (revision d4726bddaa87cc4778e7472feed243fa4b6c267f)
1 // Copyright 2015 The Bazel Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 /// Object that displays a greeting.
16 pub struct Greeter {
17     greeting: String,
18 }
19 
20 /// Implementation of Greeter.
21 impl Greeter {
22     /// Constructs a new `Greeter`.
23     ///
24     /// # Examples
25     ///
26     /// ```
27     /// use hello_lib::greeter::Greeter;
28     ///
29     /// let greeter = Greeter::new("Hello");
30     /// ```
new(greeting: &str) -> Greeter31     pub fn new(greeting: &str) -> Greeter {
32         Greeter {
33             greeting: greeting.to_string(),
34         }
35     }
36 
37     /// Returns the greeting as a string.
38     ///
39     /// # Examples
40     ///
41     /// ```
42     /// use hello_lib::greeter::Greeter;
43     ///
44     /// let greeter = Greeter::new("Hello");
45     /// let greeting = greeter.greeting("World");
46     /// ```
greeting(&self, thing: &str) -> String47     pub fn greeting(&self, thing: &str) -> String {
48         format!("{} {}", &self.greeting, thing)
49     }
50 
51     /// Prints the greeting.
52     ///
53     /// # Examples
54     ///
55     /// ```
56     /// use hello_lib::greeter::Greeter;
57     ///
58     /// let greeter = Greeter::new("Hello");
59     /// greeter.greet("World");
60     /// ```
greet(&self, thing: &str)61     pub fn greet(&self, thing: &str) {
62         println!("{} {}", &self.greeting, thing);
63     }
64 }
65 
66 #[cfg(test)]
67 mod test {
68     use super::Greeter;
69 
70     #[test]
test_greeting()71     fn test_greeting() {
72         let hello = Greeter::new("Hi");
73         assert_eq!("Hi Rust", hello.greeting("Rust"));
74     }
75 }
76