From b8600d80820164f68255507c5ef05331d0e22a56 Mon Sep 17 00:00:00 2001 From: Luc Street Date: Sun, 19 Aug 2018 22:03:16 -0700 Subject: [PATCH 1/2] rust/Types: Add reminder for different forms of 'self' parameter --- sheets/_rust/Types | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sheets/_rust/Types b/sheets/_rust/Types index cdf42fe..f549242 100644 --- a/sheets/_rust/Types +++ b/sheets/_rust/Types @@ -43,7 +43,10 @@ // Methods // impl Foo { - // Methods take an explicit `self` parameter + // Instance methods take an explicit `self` parameter. + // Using `self` on its own will consume the caller, while + // `&self` or `&mut self` will create immutable and mutable + // references, respectively. fn get_bar(self) -> T { self.bar } From 2e7ca2de6cb4a5ce7c96ce84268bea715067ec67 Mon Sep 17 00:00:00 2001 From: Luc Street Date: Sun, 19 Aug 2018 22:46:45 -0700 Subject: [PATCH 2/2] rust/Types: Static method example and turbofish - Note behavior of inferring/setting generic types --- sheets/_rust/Types | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sheets/_rust/Types b/sheets/_rust/Types index f549242..37f29ad 100644 --- a/sheets/_rust/Types +++ b/sheets/_rust/Types @@ -50,11 +50,23 @@ fn get_bar(self) -> T { self.bar } + + // Static methods don't take a `self` parameter, but can still + // use the generic `T` type. + fn do_baz(msg: &str, baz: T) -> T { + println!("{}", msg); + baz + } } + // Here `T` is inferred to be some integer type let a_foo = Foo { bar: 1 }; println!("{}", a_foo.get_bar()); // 1 + // `T` can be whatever you want, using "turbofish" syntax + // The statement below prints "Hello" and sets `result` to 24 + let result: i32 = Foo::::do_baz("Hello", 24); + // Traits (known as interfaces or typeclasses in other languages) // trait Frobnicate {