SlideShare a Scribd company logo
Traits and You:
A Deep Dive
Nell Shamrell-Harrington
@nellshamrell
Rust Belt Rust 2017
Traits are awesome!
Traits are hard…at first
I have learned to harness
the power of traits….
…And so can you!
Traits and You: A Deep Dive @nellshamrell
Nell Shamrell-Harrington
• Sr. Software Engineer at Chef
• Core maintainer of Habitat (written in Rust!)
• Seattle, WA
• @nellshamrell
• nshamrell@chef.io
@nellshamrellTraits and You: A Deep Dive
Our Journey
• 101 - Intro to Traits
• 201 - Trait Bounds
• 301 - Trait Objects
Traits 101: Intro to Traits
Traits and You: A Deep Dive @nellshamrell
Dungeons and Dragons
Yes…I have simplified
D&D rules for this
presentation
The focus of this talk is
traits with D&D used
as a metaphor
@nellshamrellTraits and You: A Deep Dive
D&D Races
Dwarf Elf Half-Orc Human
Traits and You: A Deep Dive @nellshamrell
Let’s create some structs!
struct Dwarf {
name: String
}
struct Elf {
name: String
}
Traits and You: A Deep Dive @nellshamrell
Let’s create some structs!
struct Dwarf {
name: String
}
struct Elf {
name: String
}
struct HalfOrc {
name: String
}
struct Human {
name: String
}
Traits and You: A Deep Dive @nellshamrell
Let’s make a character!
let my_dwarf = Dwarf {
name: String::from(“NellDwarf”)
};
@nellshamrellTraits and You: A Deep Dive
Character Traits
• Strength
• Dexterity
• Constitution
• Intelligence
• Wisdom
• Charisma
@nellshamrellTraits and You: A Deep Dive
Character Traits
• Strength
• Dexterity
• Constitution
• Intelligence
• Wisdom
• Charisma
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Constitution {
}
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Constitution {
fn constitution_bonus(&self) -> u8;
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
Constitution
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Constitution for Dwarf {
}
Constitution
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
Constitution
constitution_bonus
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Constitution {
fn constitution_bonus(&self) -> u8;
}
The constitution bonus
for a dwarf is 2
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Constitution for Dwarf {
fn constitution_bonus(&self) -> u8 {
}
}
Constitution
constitution_bonus
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Constitution for Dwarf {
fn constitution_bonus(&self) -> u8 {
2
}
}
Constitution
constitution_bonus
Traits and You: A Deep Dive @nellshamrell
Let’s make a character!
let my_dwarf = Dwarf {
name: String::from(“NellDwarf”)
};
Traits and You: A Deep Dive @nellshamrell
Let’s make a character!
let my_dwarf = Dwarf {
name: String::from(“NellDwarf”)
};
my_dwarf.constitution_bonus();
// Returns 2
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
struct Dwarf {
name: String
}
struct Elf {
name: String
}
struct HalfOrc {
name: String
}
struct Human {
name: String
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
Constitution
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Constitution for HalfOrc {
}
Constitution
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
Constitution
constitution_bonus
The constitution bonus
for a half-orc is 1
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Constitution for HalfOrc {
fn constitution_bonus(&self) -> u8 {
1
}
}
Constitution
constitution_bonus
Traits and You: A Deep Dive @nellshamrell
let my_half_orc = HalfOrc {
name: String::from(“NellOrc”)
};
Let’s implement that trait!
Traits and You: A Deep Dive @nellshamrell
let my_half_orc = HalfOrc {
name: String::from(“NellOrc”)
};
my_half_orc.constitution_bonus();
// Returns 1
Let’s implement that trait!
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
struct Dwarf {
name: String
}
struct Elf {
name: String
}
struct HalfOrc {
name: String
}
struct Human {
name: String
}
The constitution bonus
for both a human and
a half-elf is 0
Traits and You: A Deep Dive @nellshamrell
We could implement it like this…
impl Constitution for Elf {
fn constitution_bonus(&self) -> u8 {
0
}
}
impl Constitution for Human {
fn constitution_bonus(&self) -> u8 {
0
}
}
Traits and You: A Deep Dive @nellshamrell
We could implement it like this…
impl Constitution for Elf {
fn constitution_bonus(&self) -> u8 {
0
}
}
impl Constitution for Human {
fn constitution_bonus(&self) -> u8 {
0
}
}
Repetitive!
Most races have a
constitution bonus
of 0…
Let’s make 0 the default
Traits and You: A Deep Dive @nellshamrell
Let’s add a default!
pub trait Constitution {
fn constitution_bonus(&self) -> u8;
}
Traits and You: A Deep Dive @nellshamrell
Let’s add a default!
pub trait Constitution {
fn constitution_bonus(&self) -> u8 {
0
}
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
Constitution Constitution
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Constitution for Elf {
}
impl Constitution for Human {
}
Traits and You: A Deep Dive @nellshamrell
let my_elf = Elf {
name: String::from(“NellElf”)
};
Let’s implement that trait!
Constitution
Traits and You: A Deep Dive @nellshamrell
let my_elf = Elf {
name: String::from(“NellElf”)
};
my_elf.constitution_bonus();
// Returns 0
Let’s implement that trait!
Constitution
Traits and You: A Deep Dive @nellshamrell
let my_human = Human {
name: String::from(“Nell”)
};
Let’s implement that trait!
Constitution
Traits and You: A Deep Dive @nellshamrell
let my_human = Human {
name: String::from(“Nell”)
};
my_human.constitution_bonus();
// Returns 0
Let’s implement that trait!
Constitution
Yay! We have a trait!
Traits 201: Trait Bounds
Traits and You: A Deep Dive @nellshamrell
Dungeons and Dragons
@nellshamrellTraits and You: A Deep Dive
D&D Races
Dwarf Elf Half-Orc Human
@nellshamrellTraits and You: A Deep Dive
D&D Races
Dwarf Elf Half-Orc Human Half-Elf
@nellshamrellTraits and You: A Deep Dive
D&D Races
Dwarf Elf Half-Orc Human Half-Elf
How do they communicate?
@nellshamrellTraits and You: A Deep Dive
Languages
Dwarf Elf Half-Elf
Common, Dwarvish Common, Elvish Common, Elvish
@nellshamrellTraits and You: A Deep Dive
Languages
Dwarf Elf Half-Elf
Common, Dwarvish Common, Elvish Common, Elvish
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Elvish {
}
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Elvish {
}
impl Elvish for Elf {
}
impl Elvish for HalfElf {
}
Let’s make a function for
speaking Elvish
Traits and You: A Deep Dive @nellshamrell
Let’s make a function!
pub fn speak_elvish() -> String {
}
Traits and You: A Deep Dive @nellshamrell
Let’s make a function!
pub fn speak_elvish() -> String {
String::from(“yes”)
}
Traits and You: A Deep Dive @nellshamrell
Let’s make a function!
pub fn speak_elvish(character: T) -> String {
String::from(“yes”)
}
Accept a generic type
Traits and You: A Deep Dive @nellshamrell
Let’s make a function!
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
Only accept types
that implement
the Elvish Trait
Traits and You: A Deep Dive @nellshamrell
Let’s make a function!
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_elf = Elf { name: String::from(“NellElf”) };
Elvish
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_elf = Elf { name: String::from(“NellElf”) };
speak_elvish(my_elf)
Elvish
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Elvish {
}
impl Elvish for Elf {
}
impl Elvish for HalfElf {
}
Traits and You: A Deep Dive @nellshamrell
pub fn understand_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_elf = Elf { name: String::from(“NellElf”) };
speak_elvish(my_elf)
// Returns “yes”
Elvish
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_half_elf = HalfElf { name: String::from(“NellElf”) };
Elvish
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_half_elf = HalfElf { name: String::from(“NellElf”) };
speak_elvish(my_half_elf)
Elvish
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Elvish {
}
impl Elvish for Elf {
}
impl Elvish for HalfElf {
}
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_half_elf = HalfElf { name: String::from(“NellElf”) };
speak_elvish(my_half_elf)
// Returns “yes”
Elvish
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_half_orc = HalfOrc { name: String::from(“NellOrc”) };
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_half_orc = HalfOrc { name: String::from(“NellOrc”) };
speak_elvish(my_half_orc)
Let’s make a function!
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Elvish {
}
impl Elvish for Elf {
}
impl Elvish for HalfElf {
}
Not implemented for
Half-Orc
Traits and You: A Deep Dive @nellshamrell
pub fn speak_elvish<T: Elvish>(character: T) -> String {
String::from(“yes”)
}
let my_half_orc = HalfOrc { name: String::from(“NellOrc”) };
speak_elvish(my_half_orc)
// Returns error on compile
// The trait ‘Elvish” is not implemented for ‘HalfOrc’
Let’s make a function!
Trait bounds allow a function
to only accept types that
implement a certain trait
Traits 301: Trait Objects
Traits and You: A Deep Dive @nellshamrell
Traditional Object Oriented Languages
Object
Traits and You: A Deep Dive @nellshamrell
Traditional Object Oriented Languages
Object
Data
Behavior
Traits and You: A Deep Dive @nellshamrell
Rust
Traits and You: A Deep Dive @nellshamrell
Rust
Data
Enums/Structs
Traits and You: A Deep Dive @nellshamrell
Rust
Data Behavior
Enums/Structs Traits
Trait objects behave
more like traditional
objects
Trait objects contain
both data and behavior
Traits and You: A Deep Dive @nellshamrell
Trait Object
Trait Object
Traits and You: A Deep Dive @nellshamrell
Trait Object
Trait Object
Pointer
(Data)
Heap
Value
Traits and You: A Deep Dive @nellshamrell
Trait Object
Trait Object
Pointer
(Data)
Heap
Value
Trait
(Behavior)
You cannot add data
to a trait object
Traits and You: A Deep Dive @nellshamrell
Dungeons and Dragons
@nellshamrellTraits and You: A Deep Dive
Spells in D&D
@nellshamrellTraits and You: A Deep Dive
Spells in D&D
• Cantrip
• Transmutation
• Enchantment
• Necromancy
Traits and You: A Deep Dive @nellshamrell
Let’s create some structs!
struct Cantrip {
}
struct Transmutation {
}
struct Enchantment {
}
struct Necromancy {
}
Traits and You: A Deep Dive @nellshamrell
Let’s create some structs!
struct Cantrip {
}
struct Transmutation {
}
struct Enchantment {
}
struct Necromancy {
}
All of these need to be cast…
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Cast {
}
Traits and You: A Deep Dive @nellshamrell
Let’s make a trait!
pub trait Cast {
fn cast(&self);
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Cast for Cantrip {
fn cast(&self) {
// Details of casting a Cantrip Spell
}
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Cast for Cantrip {
fn cast(&self) {
// Details of casting a Cantrip Spell
}
}
impl Cast for Transmutation {
fn cast(&self) {
// Details of casting a Transmutation Spell
}
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Cast for Enchantment {
fn cast(&self) {
// Details of casting an Enchantment Spell
}
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement that trait!
impl Cast for Enchantment {
fn cast(&self) {
// Details of casting an Enchantment Spell
}
}
impl Cast for Necromancy {
fn cast(&self) {
// Details of casting a Necromancy Spell
}
}
Where can we keep our
spells?
@nellshamrellTraits and You: A Deep Dive
In a Spellbook, of course!
Some Cantrip
A Transmutation
Special Enchantment
Dark Necromancy
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
For casting the spell yay casting
Oh such wonderful text! Yay!
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
For casting the spell yay casting
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
For casting the spell yay casting
Oh such wonderful text! Yay!
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
struct Spellbook {
}
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
struct Spellbook {
pub spells: Vec<Box<Cast>>,
}
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
struct Spellbook {
pub spells: Vec<Box<Cast>>,
}
???
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
Vec<T>,
Vector that
contains objects
of a type
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
Vec<Box<T>>,
Traits and You: A Deep Dive @nellshamrell
Box<T>
Box
(Pointer)
Traits and You: A Deep Dive @nellshamrell
Box<T>
Box
(Pointer)
Heap
Value
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
Vec<Box<T>>,
Type of value
Box can point to
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
Vec<Box<Cast>>,
Box: must point
to a value that
implements the
Cast trait
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
struct Spellbook {
pub spells: Vec<Box<Cast>>,
}
Vector
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
struct Spellbook {
pub spells: Vec<Box<Cast>>,
}
Vector contains
Boxes
Traits and You: A Deep Dive @nellshamrell
Let’s create a struct!
struct Spellbook {
pub spells: Vec<Box<Cast>>,
}
Vector contains
Boxes that point to
values that
implement the
Cast trait
@nellshamrellTraits and You: A Deep Dive
How can we cast ALL of these?
Some Cantrip
A Transmutation
Special Enchantment
Dark Necromancy
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
For casting the spell yay casting
Oh such wonderful text! Yay!
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
For casting the spell yay casting
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
For casting the spell yay casting
Oh such wonderful text! Yay!
This is some text, here more test
For casting the spell, yay spell!
Oh such wonderful text!
This is some text for something
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
impl Spellbook {
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
impl Spellbook {
pub fn run(&self) {
}
}
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
impl Spellbook {
pub fn run(&self){
for spell in self.spells.iter() {
}
}
}
Iterate over
Spellbooks’s
spells
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
impl Spellbook {
pub fn run(&self){
for spell in self.spells.iter() {
spell.cast();
}
}
}
Cast spell
@nellshamrellTraits and You: A Deep Dive
@nellshamrellTraits and You: A Deep Dive
Run
@nellshamrellTraits and You: A Deep Dive
Cantrip
Transmutation
Enchantment
Necromancy
Run
Cast
Cast
Cast
C
ast
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
let spell_book = Spellbook {
};
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
let spell_book = Spellbook {
spells: vec![
],
};
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
let spell_book = Spellbook {
spells: vec![
Box::new(Cantrip{} ),
Box::new(Transmutation {}),
Box::new(Enchantment{}),
Box::new(Necromancy {}),
],
};
Different types
of spells
(each implements
Cast)
Traits and You: A Deep Dive @nellshamrell
Let’s implement behavior!
let spell_book = Spellbook {
spells: vec![
Box::new(Cantrip{} ),
Box::new(Transmutation {}),
Box::new(Enchantment{}),
Box::new(Necromancy {}),
],
};
spell_book.run(); Casts each spell
Trait objects are great for
heterogenus collections
It doesn’t matter what type
something is, as long as it
implements a certain trait
Wrapping up…
Traits are hard…at first
Traits are awesome!
Traits and You: A Deep Dive @nellshamrell
Where can I find out more about traits?
• Best source - The Rust Programming Language (2nd Edition)
• Traits Basics - Ch. 10.2
• Trait Bounds - Ch. 10.2
• Trait Objects - Ch. 17.2
I have learned to harness
the power of traits….
…And so can you!
Traits and You: A Deep Dive @nellshamrell
Nell Shamrell-Harrington
• Sr. Software Engineer at Chef
• Core maintainer of Habitat (written in Rust!)
• Seattle, WA
• @nellshamrell
• nshamrell@chef.io
Thank You!

More Related Content

PPTX
C# 8.0 非同期ストリーム
PDF
OPcacheの新機能ファイルベースキャッシュの内部実装を読んでみた
PDF
中3女子でもわかる constexpr
PDF
Virtualization Support in ARMv8+
PDF
Constexpr 中3女子テクニック
PPTX
知っておきたいASTERIA WARPの強制終了
PDF
Node.js with MySQL.pdf
PPTX
input type = password autocomplete = off は使ってはいけない
C# 8.0 非同期ストリーム
OPcacheの新機能ファイルベースキャッシュの内部実装を読んでみた
中3女子でもわかる constexpr
Virtualization Support in ARMv8+
Constexpr 中3女子テクニック
知っておきたいASTERIA WARPの強制終了
Node.js with MySQL.pdf
input type = password autocomplete = off は使ってはいけない

What's hot (20)

PPTX
Linux Memory Management with CMA (Contiguous Memory Allocator)
PDF
Ethernetの受信処理
PDF
Effective Modern C++ 勉強会#7 Item 27
PDF
Ninja Build: Simple Guide for Beginners
PDF
Spring Framework勉強会
PDF
PlaySQLAlchemyORM2017.key
ZIP
Rapid JCR applications development with Sling
PDF
PHP の GC の話
PDF
initramfsについて
PDF
Making Linux do Hard Real-time
PDF
がんばれ PHP Fiber
PDF
from Binary to Binary: How Qemu Works
PPTX
C#や.NET Frameworkがやっていること
PDF
20190926_Try_RHEL8_NVMEoF_Beta
PDF
The Microkernel Mach Under NeXTSTEP
PDF
OSC2011 Tokyo/Fall 濃いバナ(virtio)
PPTX
ASTERIA WARP運用Tips「RDB連携時のトラブルシューティング 」
PPTX
Memory model
PPTX
【古いスライド】〜僕の初めてのリアクティブプログラミング Reactor を使ってリアクティブに昇龍拳を繰り出してみた!
PDF
Portacle : Common Lispのオールインワン開発環境
Linux Memory Management with CMA (Contiguous Memory Allocator)
Ethernetの受信処理
Effective Modern C++ 勉強会#7 Item 27
Ninja Build: Simple Guide for Beginners
Spring Framework勉強会
PlaySQLAlchemyORM2017.key
Rapid JCR applications development with Sling
PHP の GC の話
initramfsについて
Making Linux do Hard Real-time
がんばれ PHP Fiber
from Binary to Binary: How Qemu Works
C#や.NET Frameworkがやっていること
20190926_Try_RHEL8_NVMEoF_Beta
The Microkernel Mach Under NeXTSTEP
OSC2011 Tokyo/Fall 濃いバナ(virtio)
ASTERIA WARP運用Tips「RDB連携時のトラブルシューティング 」
Memory model
【古いスライド】〜僕の初めてのリアクティブプログラミング Reactor を使ってリアクティブに昇龍拳を繰り出してみた!
Portacle : Common Lispのオールインワン開発環境
Ad

More from Nell Shamrell-Harrington (20)

PDF
This Week in Rust: 400 Issues and Counting!
PDF
The Rust Borrow Checker
PPTX
Higher. Faster. Stronger. Your Applications with Habitat
PDF
Habitat Service Discovery
PDF
Web Operations101
PDF
Rust, Redis, and Protobuf - Oh My!
PDF
Containers, Virtual Machines, and Bare Metal, Oh My!
PDF
Chef Vault: A Deep Dive
PDF
Open Source Governance 101
PDF
DevOps in Politics
PDF
Open Source Governance - The Hard Parts
PPTX
Creating Packages that Run Anywhere with Chef Habitat
PDF
Refactoring terraform
PDF
Refactoring Infrastructure Code
PDF
Devops: A History
PDF
First Do No Harm: Surgical Refactoring (extended edition)
PDF
First Do No Harm: Surgical Refactoring
PPTX
A Supermarket of Your Own: Running a Private Chef Supermarket
PPTX
Public Supermarket: The Insider's Tour
PDF
Beneath the Surface - Rubyconf 2013
This Week in Rust: 400 Issues and Counting!
The Rust Borrow Checker
Higher. Faster. Stronger. Your Applications with Habitat
Habitat Service Discovery
Web Operations101
Rust, Redis, and Protobuf - Oh My!
Containers, Virtual Machines, and Bare Metal, Oh My!
Chef Vault: A Deep Dive
Open Source Governance 101
DevOps in Politics
Open Source Governance - The Hard Parts
Creating Packages that Run Anywhere with Chef Habitat
Refactoring terraform
Refactoring Infrastructure Code
Devops: A History
First Do No Harm: Surgical Refactoring (extended edition)
First Do No Harm: Surgical Refactoring
A Supermarket of Your Own: Running a Private Chef Supermarket
Public Supermarket: The Insider's Tour
Beneath the Surface - Rubyconf 2013
Ad

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Getting Started with Data Integration: FME Form 101
PDF
Electronic commerce courselecture one. Pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Machine Learning_overview_presentation.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
A Presentation on Artificial Intelligence
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation theory and applications.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
Spectroscopy.pptx food analysis technology
PPT
Teaching material agriculture food technology
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Getting Started with Data Integration: FME Form 101
Electronic commerce courselecture one. Pdf
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
SOPHOS-XG Firewall Administrator PPT.pptx
Machine Learning_overview_presentation.pptx
Big Data Technologies - Introduction.pptx
A Presentation on Artificial Intelligence
Digital-Transformation-Roadmap-for-Companies.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation theory and applications.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Spectroscopy.pptx food analysis technology
Teaching material agriculture food technology
Assigned Numbers - 2025 - Bluetooth® Document
Advanced methodologies resolving dimensionality complications for autism neur...
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

Rust Traits And You: A Deep Dive

  • 1. Traits and You: A Deep Dive Nell Shamrell-Harrington @nellshamrell Rust Belt Rust 2017
  • 4. I have learned to harness the power of traits….
  • 6. Traits and You: A Deep Dive @nellshamrell Nell Shamrell-Harrington • Sr. Software Engineer at Chef • Core maintainer of Habitat (written in Rust!) • Seattle, WA • @nellshamrell • nshamrell@chef.io
  • 7. @nellshamrellTraits and You: A Deep Dive Our Journey • 101 - Intro to Traits • 201 - Trait Bounds • 301 - Trait Objects
  • 8. Traits 101: Intro to Traits
  • 9. Traits and You: A Deep Dive @nellshamrell Dungeons and Dragons
  • 10. Yes…I have simplified D&D rules for this presentation
  • 11. The focus of this talk is traits with D&D used as a metaphor
  • 12. @nellshamrellTraits and You: A Deep Dive D&D Races Dwarf Elf Half-Orc Human
  • 13. Traits and You: A Deep Dive @nellshamrell Let’s create some structs! struct Dwarf { name: String } struct Elf { name: String }
  • 14. Traits and You: A Deep Dive @nellshamrell Let’s create some structs! struct Dwarf { name: String } struct Elf { name: String } struct HalfOrc { name: String } struct Human { name: String }
  • 15. Traits and You: A Deep Dive @nellshamrell Let’s make a character! let my_dwarf = Dwarf { name: String::from(“NellDwarf”) };
  • 16. @nellshamrellTraits and You: A Deep Dive Character Traits • Strength • Dexterity • Constitution • Intelligence • Wisdom • Charisma
  • 17. @nellshamrellTraits and You: A Deep Dive Character Traits • Strength • Dexterity • Constitution • Intelligence • Wisdom • Charisma
  • 18. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Constitution { }
  • 19. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Constitution { fn constitution_bonus(&self) -> u8; }
  • 20. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! Constitution
  • 21. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Constitution for Dwarf { } Constitution
  • 22. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! Constitution constitution_bonus
  • 23. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Constitution { fn constitution_bonus(&self) -> u8; }
  • 25. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Constitution for Dwarf { fn constitution_bonus(&self) -> u8 { } } Constitution constitution_bonus
  • 26. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Constitution for Dwarf { fn constitution_bonus(&self) -> u8 { 2 } } Constitution constitution_bonus
  • 27. Traits and You: A Deep Dive @nellshamrell Let’s make a character! let my_dwarf = Dwarf { name: String::from(“NellDwarf”) };
  • 28. Traits and You: A Deep Dive @nellshamrell Let’s make a character! let my_dwarf = Dwarf { name: String::from(“NellDwarf”) }; my_dwarf.constitution_bonus(); // Returns 2
  • 29. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! struct Dwarf { name: String } struct Elf { name: String } struct HalfOrc { name: String } struct Human { name: String }
  • 30. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! Constitution
  • 31. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Constitution for HalfOrc { } Constitution
  • 32. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! Constitution constitution_bonus
  • 33. The constitution bonus for a half-orc is 1
  • 34. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Constitution for HalfOrc { fn constitution_bonus(&self) -> u8 { 1 } } Constitution constitution_bonus
  • 35. Traits and You: A Deep Dive @nellshamrell let my_half_orc = HalfOrc { name: String::from(“NellOrc”) }; Let’s implement that trait!
  • 36. Traits and You: A Deep Dive @nellshamrell let my_half_orc = HalfOrc { name: String::from(“NellOrc”) }; my_half_orc.constitution_bonus(); // Returns 1 Let’s implement that trait!
  • 37. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! struct Dwarf { name: String } struct Elf { name: String } struct HalfOrc { name: String } struct Human { name: String }
  • 38. The constitution bonus for both a human and a half-elf is 0
  • 39. Traits and You: A Deep Dive @nellshamrell We could implement it like this… impl Constitution for Elf { fn constitution_bonus(&self) -> u8 { 0 } } impl Constitution for Human { fn constitution_bonus(&self) -> u8 { 0 } }
  • 40. Traits and You: A Deep Dive @nellshamrell We could implement it like this… impl Constitution for Elf { fn constitution_bonus(&self) -> u8 { 0 } } impl Constitution for Human { fn constitution_bonus(&self) -> u8 { 0 } } Repetitive!
  • 41. Most races have a constitution bonus of 0…
  • 42. Let’s make 0 the default
  • 43. Traits and You: A Deep Dive @nellshamrell Let’s add a default! pub trait Constitution { fn constitution_bonus(&self) -> u8; }
  • 44. Traits and You: A Deep Dive @nellshamrell Let’s add a default! pub trait Constitution { fn constitution_bonus(&self) -> u8 { 0 } }
  • 45. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! Constitution Constitution
  • 46. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Constitution for Elf { } impl Constitution for Human { }
  • 47. Traits and You: A Deep Dive @nellshamrell let my_elf = Elf { name: String::from(“NellElf”) }; Let’s implement that trait! Constitution
  • 48. Traits and You: A Deep Dive @nellshamrell let my_elf = Elf { name: String::from(“NellElf”) }; my_elf.constitution_bonus(); // Returns 0 Let’s implement that trait! Constitution
  • 49. Traits and You: A Deep Dive @nellshamrell let my_human = Human { name: String::from(“Nell”) }; Let’s implement that trait! Constitution
  • 50. Traits and You: A Deep Dive @nellshamrell let my_human = Human { name: String::from(“Nell”) }; my_human.constitution_bonus(); // Returns 0 Let’s implement that trait! Constitution
  • 51. Yay! We have a trait!
  • 53. Traits and You: A Deep Dive @nellshamrell Dungeons and Dragons
  • 54. @nellshamrellTraits and You: A Deep Dive D&D Races Dwarf Elf Half-Orc Human
  • 55. @nellshamrellTraits and You: A Deep Dive D&D Races Dwarf Elf Half-Orc Human Half-Elf
  • 56. @nellshamrellTraits and You: A Deep Dive D&D Races Dwarf Elf Half-Orc Human Half-Elf How do they communicate?
  • 57. @nellshamrellTraits and You: A Deep Dive Languages Dwarf Elf Half-Elf Common, Dwarvish Common, Elvish Common, Elvish
  • 58. @nellshamrellTraits and You: A Deep Dive Languages Dwarf Elf Half-Elf Common, Dwarvish Common, Elvish Common, Elvish
  • 59. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Elvish { }
  • 60. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Elvish { } impl Elvish for Elf { } impl Elvish for HalfElf { }
  • 61. Let’s make a function for speaking Elvish
  • 62. Traits and You: A Deep Dive @nellshamrell Let’s make a function! pub fn speak_elvish() -> String { }
  • 63. Traits and You: A Deep Dive @nellshamrell Let’s make a function! pub fn speak_elvish() -> String { String::from(“yes”) }
  • 64. Traits and You: A Deep Dive @nellshamrell Let’s make a function! pub fn speak_elvish(character: T) -> String { String::from(“yes”) } Accept a generic type
  • 65. Traits and You: A Deep Dive @nellshamrell Let’s make a function! pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } Only accept types that implement the Elvish Trait
  • 66. Traits and You: A Deep Dive @nellshamrell Let’s make a function! pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_elf = Elf { name: String::from(“NellElf”) }; Elvish
  • 67. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_elf = Elf { name: String::from(“NellElf”) }; speak_elvish(my_elf) Elvish Let’s make a function!
  • 68. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Elvish { } impl Elvish for Elf { } impl Elvish for HalfElf { }
  • 69. Traits and You: A Deep Dive @nellshamrell pub fn understand_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_elf = Elf { name: String::from(“NellElf”) }; speak_elvish(my_elf) // Returns “yes” Elvish Let’s make a function!
  • 70. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_half_elf = HalfElf { name: String::from(“NellElf”) }; Elvish Let’s make a function!
  • 71. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_half_elf = HalfElf { name: String::from(“NellElf”) }; speak_elvish(my_half_elf) Elvish Let’s make a function!
  • 72. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Elvish { } impl Elvish for Elf { } impl Elvish for HalfElf { }
  • 73. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_half_elf = HalfElf { name: String::from(“NellElf”) }; speak_elvish(my_half_elf) // Returns “yes” Elvish Let’s make a function!
  • 74. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_half_orc = HalfOrc { name: String::from(“NellOrc”) }; Let’s make a function!
  • 75. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_half_orc = HalfOrc { name: String::from(“NellOrc”) }; speak_elvish(my_half_orc) Let’s make a function!
  • 76. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Elvish { } impl Elvish for Elf { } impl Elvish for HalfElf { } Not implemented for Half-Orc
  • 77. Traits and You: A Deep Dive @nellshamrell pub fn speak_elvish<T: Elvish>(character: T) -> String { String::from(“yes”) } let my_half_orc = HalfOrc { name: String::from(“NellOrc”) }; speak_elvish(my_half_orc) // Returns error on compile // The trait ‘Elvish” is not implemented for ‘HalfOrc’ Let’s make a function!
  • 78. Trait bounds allow a function to only accept types that implement a certain trait
  • 79. Traits 301: Trait Objects
  • 80. Traits and You: A Deep Dive @nellshamrell Traditional Object Oriented Languages Object
  • 81. Traits and You: A Deep Dive @nellshamrell Traditional Object Oriented Languages Object Data Behavior
  • 82. Traits and You: A Deep Dive @nellshamrell Rust
  • 83. Traits and You: A Deep Dive @nellshamrell Rust Data Enums/Structs
  • 84. Traits and You: A Deep Dive @nellshamrell Rust Data Behavior Enums/Structs Traits
  • 85. Trait objects behave more like traditional objects
  • 86. Trait objects contain both data and behavior
  • 87. Traits and You: A Deep Dive @nellshamrell Trait Object Trait Object
  • 88. Traits and You: A Deep Dive @nellshamrell Trait Object Trait Object Pointer (Data) Heap Value
  • 89. Traits and You: A Deep Dive @nellshamrell Trait Object Trait Object Pointer (Data) Heap Value Trait (Behavior)
  • 90. You cannot add data to a trait object
  • 91. Traits and You: A Deep Dive @nellshamrell Dungeons and Dragons
  • 92. @nellshamrellTraits and You: A Deep Dive Spells in D&D
  • 93. @nellshamrellTraits and You: A Deep Dive Spells in D&D • Cantrip • Transmutation • Enchantment • Necromancy
  • 94. Traits and You: A Deep Dive @nellshamrell Let’s create some structs! struct Cantrip { } struct Transmutation { } struct Enchantment { } struct Necromancy { }
  • 95. Traits and You: A Deep Dive @nellshamrell Let’s create some structs! struct Cantrip { } struct Transmutation { } struct Enchantment { } struct Necromancy { } All of these need to be cast…
  • 96. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Cast { }
  • 97. Traits and You: A Deep Dive @nellshamrell Let’s make a trait! pub trait Cast { fn cast(&self); }
  • 98. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Cast for Cantrip { fn cast(&self) { // Details of casting a Cantrip Spell } }
  • 99. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Cast for Cantrip { fn cast(&self) { // Details of casting a Cantrip Spell } } impl Cast for Transmutation { fn cast(&self) { // Details of casting a Transmutation Spell } }
  • 100. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Cast for Enchantment { fn cast(&self) { // Details of casting an Enchantment Spell } }
  • 101. Traits and You: A Deep Dive @nellshamrell Let’s implement that trait! impl Cast for Enchantment { fn cast(&self) { // Details of casting an Enchantment Spell } } impl Cast for Necromancy { fn cast(&self) { // Details of casting a Necromancy Spell } }
  • 102. Where can we keep our spells?
  • 103. @nellshamrellTraits and You: A Deep Dive In a Spellbook, of course! Some Cantrip A Transmutation Special Enchantment Dark Necromancy This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something For casting the spell yay casting Oh such wonderful text! Yay! This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something For casting the spell yay casting This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something For casting the spell yay casting Oh such wonderful text! Yay! This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something
  • 104. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! struct Spellbook { }
  • 105. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! struct Spellbook { pub spells: Vec<Box<Cast>>, }
  • 106. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! struct Spellbook { pub spells: Vec<Box<Cast>>, } ???
  • 107. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! Vec<T>, Vector that contains objects of a type
  • 108. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! Vec<Box<T>>,
  • 109. Traits and You: A Deep Dive @nellshamrell Box<T> Box (Pointer)
  • 110. Traits and You: A Deep Dive @nellshamrell Box<T> Box (Pointer) Heap Value
  • 111. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! Vec<Box<T>>, Type of value Box can point to
  • 112. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! Vec<Box<Cast>>, Box: must point to a value that implements the Cast trait
  • 113. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! struct Spellbook { pub spells: Vec<Box<Cast>>, } Vector
  • 114. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! struct Spellbook { pub spells: Vec<Box<Cast>>, } Vector contains Boxes
  • 115. Traits and You: A Deep Dive @nellshamrell Let’s create a struct! struct Spellbook { pub spells: Vec<Box<Cast>>, } Vector contains Boxes that point to values that implement the Cast trait
  • 116. @nellshamrellTraits and You: A Deep Dive How can we cast ALL of these? Some Cantrip A Transmutation Special Enchantment Dark Necromancy This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something For casting the spell yay casting Oh such wonderful text! Yay! This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something For casting the spell yay casting This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something For casting the spell yay casting Oh such wonderful text! Yay! This is some text, here more test For casting the spell, yay spell! Oh such wonderful text! This is some text for something
  • 117. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! impl Spellbook { }
  • 118. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! impl Spellbook { pub fn run(&self) { } }
  • 119. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! impl Spellbook { pub fn run(&self){ for spell in self.spells.iter() { } } } Iterate over Spellbooks’s spells
  • 120. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! impl Spellbook { pub fn run(&self){ for spell in self.spells.iter() { spell.cast(); } } } Cast spell
  • 122. @nellshamrellTraits and You: A Deep Dive Run
  • 123. @nellshamrellTraits and You: A Deep Dive Cantrip Transmutation Enchantment Necromancy Run Cast Cast Cast C ast
  • 124. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! let spell_book = Spellbook { };
  • 125. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! let spell_book = Spellbook { spells: vec![ ], };
  • 126. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! let spell_book = Spellbook { spells: vec![ Box::new(Cantrip{} ), Box::new(Transmutation {}), Box::new(Enchantment{}), Box::new(Necromancy {}), ], }; Different types of spells (each implements Cast)
  • 127. Traits and You: A Deep Dive @nellshamrell Let’s implement behavior! let spell_book = Spellbook { spells: vec![ Box::new(Cantrip{} ), Box::new(Transmutation {}), Box::new(Enchantment{}), Box::new(Necromancy {}), ], }; spell_book.run(); Casts each spell
  • 128. Trait objects are great for heterogenus collections
  • 129. It doesn’t matter what type something is, as long as it implements a certain trait
  • 133. Traits and You: A Deep Dive @nellshamrell Where can I find out more about traits? • Best source - The Rust Programming Language (2nd Edition) • Traits Basics - Ch. 10.2 • Trait Bounds - Ch. 10.2 • Trait Objects - Ch. 17.2
  • 134. I have learned to harness the power of traits….
  • 135. …And so can you!
  • 136. Traits and You: A Deep Dive @nellshamrell Nell Shamrell-Harrington • Sr. Software Engineer at Chef • Core maintainer of Habitat (written in Rust!) • Seattle, WA • @nellshamrell • nshamrell@chef.io Thank You!