Add advanced_traits example

This commit is contained in:
Timothy Warren 2019-02-07 13:31:29 -05:00
parent 13233d5eb1
commit d2535d80a8
5 changed files with 230 additions and 46 deletions

View File

@ -38,6 +38,7 @@
<cargoProject FILE="$PROJECT_DIR$/pattern_matching/Cargo.toml" />
<cargoProject FILE="$PROJECT_DIR$/unsafe_blocks/Cargo.toml" />
<cargoProject FILE="$PROJECT_DIR$/advanced_lifetimes/Cargo.toml" />
<cargoProject FILE="$PROJECT_DIR$/advanced_traits/Cargo.toml" />
</component>
<component name="ComposerJsonPluginSettings">
<unboundedVersionInspectionSettings>

View File

@ -153,10 +153,15 @@
<sourceFolder url="file://$MODULE_DIR$/advanced_lifetimes/examples" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/advanced_lifetimes/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/advanced_lifetimes/benches" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/advanced_traits/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/advanced_traits/examples" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/advanced_traits/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/advanced_traits/benches" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/add/add-one/target" />
<excludeFolder url="file://$MODULE_DIR$/add/adder/target" />
<excludeFolder url="file://$MODULE_DIR$/adder/target" />
<excludeFolder url="file://$MODULE_DIR$/advanced_lifetimes/target" />
<excludeFolder url="file://$MODULE_DIR$/advanced_traits/target" />
<excludeFolder url="file://$MODULE_DIR$/blog/target" />
<excludeFolder url="file://$MODULE_DIR$/branches/target" />
<excludeFolder url="file://$MODULE_DIR$/closures/target" />

View File

@ -14,30 +14,36 @@
</component>
<component name="FileEditorManager">
<leaf>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/advanced_lifetimes/src/lib.rs">
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/advanced_traits/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="272">
<caret line="17" column="20" selection-start-line="17" selection-start-column="20" selection-end-line="17" selection-end-column="20" />
<state relative-caret-position="1221">
<caret line="147" column="4" selection-start-line="147" selection-start-column="4" selection-end-line="147" selection-end-column="4" />
<folding>
<element signature="e#237#238#0" expanded="true" />
<element signature="e#277#278#0" expanded="true" />
<element signature="e#337#338#0" expanded="true" />
<element signature="e#380#381#0" expanded="true" />
<element signature="e#438#439#0" expanded="true" />
<element signature="e#474#475#0" expanded="true" />
<element signature="e#444#445#0" expanded="true" />
<element signature="e#470#471#0" expanded="true" />
<element signature="e#793#794#0" expanded="true" />
<element signature="e#818#819#0" expanded="true" />
<element signature="e#898#899#0" expanded="true" />
<element signature="e#923#924#0" expanded="true" />
<element signature="e#965#966#0" expanded="true" />
<element signature="e#990#991#0" expanded="true" />
<element signature="e#1279#1280#0" expanded="true" />
<element signature="e#1308#1309#0" expanded="true" />
<element signature="e#1370#1371#0" expanded="true" />
<element signature="e#1399#1400#0" expanded="true" />
<element signature="e#2048#2049#0" expanded="true" />
<element signature="e#2071#2072#0" expanded="true" />
<element signature="e#2642#2643#0" expanded="true" />
<element signature="e#2665#2666#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/advanced_lifetimes/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="10" column="59" selection-start-line="10" selection-start-column="59" selection-end-line="10" selection-end-column="59" />
</state>
</provider>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/advanced_traits/src/lib.rs">
<provider selected="true" editor-type-id="text-editor" />
</entry>
</file>
</leaf>
@ -69,8 +75,6 @@
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/modules/src/performance_group.rs" />
<option value="$PROJECT_DIR$/modules/src/main.rs" />
<option value="$PROJECT_DIR$/modules/src/sound/instrument.rs" />
<option value="$PROJECT_DIR$/guessing_game/.gitignore" />
<option value="$PROJECT_DIR$/errors/src/main.rs" />
@ -120,6 +124,8 @@
<option value="$PROJECT_DIR$/unsafe_blocks/src/main.rs" />
<option value="$PROJECT_DIR$/advanced_lifetimes/src/lib.rs" />
<option value="$PROJECT_DIR$/advanced_lifetimes/src/main.rs" />
<option value="$PROJECT_DIR$/advanced_traits/src/lib.rs" />
<option value="$PROJECT_DIR$/advanced_traits/src/main.rs" />
</list>
</option>
</component>
@ -153,12 +159,12 @@
<path>
<item name="rust" type="3d21c010:ScopeViewTreeModel$ProjectNode" />
<item name="rust" type="2674bda8:ScopeViewTreeModel$GroupNode" />
<item name="advanced_lifetimes" type="9f88c78c:ScopeViewTreeModel$FileNode" />
<item name="advanced_traits" type="9f88c78c:ScopeViewTreeModel$FileNode" />
</path>
<path>
<item name="rust" type="3d21c010:ScopeViewTreeModel$ProjectNode" />
<item name="rust" type="2674bda8:ScopeViewTreeModel$GroupNode" />
<item name="advanced_lifetimes" type="9f88c78c:ScopeViewTreeModel$FileNode" />
<item name="advanced_traits" type="9f88c78c:ScopeViewTreeModel$FileNode" />
<item name="src" type="9f88c78c:ScopeViewTreeModel$FileNode" />
</path>
</expand>
@ -192,7 +198,7 @@
</component>
<component name="PropertiesComponent">
<property name="JavaScriptWeakerCompletionTypeGuess" value="true" />
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1549560474400" />
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1549564268156" />
<property name="javascript.nodejs.core.library.configured.version" value="7.1.0" />
<property name="js.eslint.eslintPackage" value="$USER_HOME$/.yarn-config/global/node_modules/.bin/eslint" />
<property name="js.eslint.nodeInterpreter" value="project" />
@ -220,7 +226,7 @@
</list>
</option>
</component>
<component name="RunManager" selected="Cargo Command.Run advanced_lifetimes">
<component name="RunManager" selected="Cargo Command.Run advanced_traits">
<configuration name="&lt;template&gt;" type="TestNG" default="true" selected="false">
<option name="MAIN_CLASS_NAME" />
<option name="VM_PARAMETERS" value="-ea" />
@ -249,13 +255,13 @@
<envs />
<method v="2" />
</configuration>
<configuration name="Run pattern_matching" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<configuration name="Run advanced_traits" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<option name="channel" value="DEFAULT" />
<option name="command" value="run --package pattern_matching --bin pattern_matching" />
<option name="command" value="run --package advanced_traits --bin advanced_traits" />
<option name="allFeatures" value="false" />
<option name="nocapture" value="false" />
<option name="backtrace" value="SHORT" />
<option name="workingDirectory" value="file://$PROJECT_DIR$/pattern_matching" />
<option name="workingDirectory" value="file://$PROJECT_DIR$/advanced_traits" />
<envs />
<method v="2" />
</configuration>
@ -298,11 +304,11 @@
</configuration>
<recent_temporary>
<list>
<item itemvalue="Cargo Command.Run advanced_traits" />
<item itemvalue="Cargo Command.Run advanced_lifetimes" />
<item itemvalue="Cargo Command.Test lib::tests" />
<item itemvalue="Cargo Command.Test tests::it_works" />
<item itemvalue="Cargo Command.Run unsafe_blocks" />
<item itemvalue="Cargo Command.Run pattern_matching" />
</list>
</recent_temporary>
</component>
@ -373,20 +379,6 @@
<option name="version" value="1" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/.idea/workspace.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="368">
<caret line="23" column="40" selection-start-line="23" selection-start-column="40" selection-end-line="23" selection-end-column="40" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/enums/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="672">
<caret line="42" column="16" lean-forward="true" selection-start-line="42" selection-start-column="16" selection-end-line="42" selection-end-column="16" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/modules/src/sound.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="16">
@ -793,10 +785,17 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/advanced_lifetimes/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="304">
<caret line="19" lean-forward="true" selection-start-line="19" selection-end-line="19" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/advanced_lifetimes/src/lib.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="272">
<caret line="17" column="20" selection-start-line="17" selection-start-column="20" selection-end-line="17" selection-end-column="20" />
<state relative-caret-position="416">
<caret line="26" lean-forward="true" selection-start-line="26" selection-end-line="26" />
<folding>
<element signature="e#237#238#0" expanded="true" />
<element signature="e#277#278#0" expanded="true" />
@ -808,10 +807,31 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/advanced_lifetimes/src/main.rs">
<entry file="file://$PROJECT_DIR$/advanced_traits/src/lib.rs">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/advanced_traits/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="10" column="59" selection-start-line="10" selection-start-column="59" selection-end-line="10" selection-end-column="59" />
<state relative-caret-position="1221">
<caret line="147" column="4" selection-start-line="147" selection-start-column="4" selection-end-line="147" selection-end-column="4" />
<folding>
<element signature="e#444#445#0" expanded="true" />
<element signature="e#470#471#0" expanded="true" />
<element signature="e#793#794#0" expanded="true" />
<element signature="e#818#819#0" expanded="true" />
<element signature="e#898#899#0" expanded="true" />
<element signature="e#923#924#0" expanded="true" />
<element signature="e#965#966#0" expanded="true" />
<element signature="e#990#991#0" expanded="true" />
<element signature="e#1279#1280#0" expanded="true" />
<element signature="e#1308#1309#0" expanded="true" />
<element signature="e#1370#1371#0" expanded="true" />
<element signature="e#1399#1400#0" expanded="true" />
<element signature="e#2048#2049#0" expanded="true" />
<element signature="e#2071#2072#0" expanded="true" />
<element signature="e#2642#2643#0" expanded="true" />
<element signature="e#2665#2666#0" expanded="true" />
</folding>
</state>
</provider>
</entry>

View File

@ -0,0 +1,7 @@
[package]
name = "advanced_traits"
version = "0.1.0"
authors = ["Timothy Warren <twarren@nabancard.com>"]
edition = "2018"
[dependencies]

151
advanced_traits/src/main.rs Normal file
View File

@ -0,0 +1,151 @@
use std::fmt;
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
struct Millimeters(u32);
struct Meters(u32);
/// Implement the Add trait to allow adding
/// The value from a Meters type to a Millimeters type
///
/// The Add<Meters> allows the cross-type operator overloading
impl Add<Meters> for Millimeters {
type Output = Millimeters;
fn add(self, other: Meters) -> Millimeters {
Millimeters(self.0 + (other.0 * 1000))
}
}
// ----------------------------------------------------------
// Fully qualified method calls
// ----------------------------------------------------------
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human;
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("Up!");
}
}
impl Human {
fn fly(&self) {
println!("*waving arms furiously*");
}
}
trait Animal {
fn baby_name() -> String;
}
struct Dog;
impl Dog {
fn baby_name() -> String {
String::from("Spot")
}
}
impl Animal for Dog {
fn baby_name() -> String {
String::from("puppy")
}
}
// ----------------------------------------------------------
// Supertraits
// ----------------------------------------------------------
/// This trait requires the supertrait, `fmt::Display` to be
/// implemented to consider itself implemented
trait OutlinePrint: fmt::Display {
fn outline_print(&self) {
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {} *", output);
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
impl OutlinePrint for Point {}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
// -------------------------------------------------------------
// Newtype pattern (Implement external traits on external types)
// -------------------------------------------------------------
// Wrap an external type in tuple struct, so it is now local
struct Wrapper(Vec<String>);
// Implement an extenal trait for the now local type
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fm::Formatter) -> fmt::Result {
write!(f, "[{}]", self.0.join(", "))
}
}
// ----------------------------------------------------------
fn main() {
assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
Point { x: 3, y: 3 });
let person = Human;
// Explicitly specifying which implementation to use
Pilot::fly(&person);
Wizard::fly(&person);
// Defaults to the direct implementation
// aka: Human::fly(&person);
person.fly();
// Specify the implementation to use for an associated function
// implemented multiple ways with the same name
println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
let display_point = Point { x: 5, y: -3 };
display_point.outline_print();
let w = Wrapper(vec![String::from("hello"), String::from("world")]);
println!("w = {}", w);
}