SlideShare a Scribd company logo
Writing Rust CLI ApplicationsWriting Rust CLI Applications
Jean-Marcel BelmontJean-Marcel Belmont
Senior Software EngineerSenior Software Engineer
What is a cli anyway?What is a cli anyway?
“ A command-line interface or command language interpreter
(CLI), also known as command-line user interface, console user
interface[1] and character user interface (CUI), is a means of
interacting with a computer program where the user (or client)
issues commands to the program in the form of successive lines of
text (command lines). A program which handles the interface is
called a command language interpreter or shell (computing).
According to wikipedia:
clis are for hackers rightclis are for hackers right
Who needs clis I have my IDEWho needs clis I have my IDE
I press F5 and boom I am golden!!!I press F5 and boom I am golden!!!
Let the CLI Cookoff begin!!Let the CLI Cookoff begin!!
CLI program that computes a sum in Rust.CLI program that computes a sum in Rust.
Rust has several different ways to iterate through collections!
We can use a for in loop with Rust.We can use a for in loop with Rust.
Notice that we didn't put a return statement here!Notice that we didn't put a return statement here!
sum is an expression and will return.sum is an expression and will return.
We can use iterator methods to do the same actionWe can use iterator methods to do the same action
foldfold is an iterator method that applies ais an iterator method that applies a
function, producing a single, final value.function, producing a single, final value.
Notice here that we used the explicit return statement here!Notice here that we used the explicit return statement here!
Using the return statement like this is not considered idiomatic.Using the return statement like this is not considered idiomatic.
Demo!Demo!
Same summation program in Golang
CLI program that computes sum in GolangCLI program that computes sum in Golang
Here is a sum function for the Go Program
In Go you will typically use a for loop to iterate through collections.
Run sum program in go with this commandRun sum program in go with this command
Here we pass in our arguments after we run the main.go program
Alternatively you can build your program and then run the binary!
Demo!Demo!
Making an HTTP RequestMaking an HTTP Request
Let us write a Rust Script that makes an HTTP Request
Here we use the library to make an HTTP requestreqwest
Here is the main programHere is the main program
Here I put a sleep so that I could quickly copy theHere I put a sleep so that I could quickly copy the
standard output of this command!standard output of this command!
The tee command will spit out standard output andThe tee command will spit out standard output and
create a file for us in one go.create a file for us in one go.
Demo this script!!Demo this script!!
Same Program with GolangSame Program with Golang
Golang has a standard library that you can use toGolang has a standard library that you can use to
make http calls!make http calls!
No 3rd Party Libraries neededNo 3rd Party Libraries needed
You can use this handy online tool to convert jsonYou can use this handy online tool to convert json
schemas into Go Structsschemas into Go Structs
Here is the main program that makes an http requestHere is the main program that makes an http request
to Travis CI API.to Travis CI API.
Here is the rest of the programHere is the rest of the program
Notice here that I renamed the Autogenerated Name to ReposNotice here that I renamed the Autogenerated Name to Repos
Demo Time!!!Demo Time!!!
Lets Test our Rust CLILets Test our Rust CLI
programs!!programs!!
Changing the structure of the summation program for testingChanging the structure of the summation program for testing
Here we supply an option ofHere we supply an option of --lib--lib to cargo and it generates ato cargo and it generates a lib.rslib.rs
Notice that cargo generated a test for us in a file calledNotice that cargo generated a test for us in a file called lib.rslib.rs
We will break apart the 2 summation functions from the main.rs into the
lib.rs
Notice here that we add pub for public visibility
Notice here that we now use our lib as an internal crate!
We call our public method with the crate name now.
We add the following annotation to create our unit test cases.
Now we can unit test our cli program by issuing the cargo test command
Notice here that both of our unit test cases run when we run cargo test!
Demo Building average cli program!Demo Building average cli program!
Testing with GolangTesting with Golang
Let us unit test our summer cli programLet us unit test our summer cli program
We simply create a file withWe simply create a file with _test.go_test.go to writeto write
tests in Golangtests in Golang
We import the testing package into main_test.goWe import the testing package into main_test.go
Notice here that we assert numbers should not equal 12.0.Notice here that we assert numbers should not equal 12.0.
Let us run the Go Test fileLet us run the Go Test file
Hacking with the Rust clap libraryHacking with the Rust clap library
Using Clap to build Robust Clis in Rust
Clap has many features to build robust features
Using Clap to build Robust Clis in Rust
let matches = App::new("Calculator")
.subcommand(SubCommand::with_name("add")
.about("Sum some numbers")
.version("0.1")
.author("Jean-Marcel Belmont")
.arg(Arg::with_name("numbers")
.multiple(true)
.help("the numbers to add")
.required(true)))
.subcommand(SubCommand::with_name("subtract")
.about("Subtract some numbers")
.version("0.1")
.author("Jean-Marcel Belmont")
.arg(Arg::with_name("numbers")
.multiple(true)
.help("the numbers to subtract")
.index(1)
.required(true)))
Here we use subcommands to build a calculator cli application
Here we run the binary executable to run our simple
calculator cli application
Notice that each subcommand performs a different calculation.
Also notice that we are using the binary executable here.
 
It is created upon successful `cargo run` and/or `cargo build`.
DemoDemo!!!!!!
Let us look at the cobraLet us look at the cobra
No not the movie Cobra with Slyvester Stallone!No not the movie Cobra with Slyvester Stallone!
Let us look at the Golang CLI Library.Let us look at the Golang CLI Library.
Here we create a cli application with cobra init command!
We then create a symbolic link to it in this directory
Here we initialize a cobra yaml file for common info!
Now we finally create our main calculator logic.
Here is bulk of the logic for add, subtract, multiply, and divide
We have a cobra.Command and supply our function to run!
The first command runs the add subcommand.
The second command builds the binary executable.
The third command runs the binary executable and runs the
subtract subcommand.
Each command afterwards is demonstrating the other
subcommands in the calculator program.
Demo!!!Demo!!!
Let's Check off parsing, serialization, andLet's Check off parsing, serialization, and
deserialization of our Rust Bucket List Nextdeserialization of our Rust Bucket List Next
Data Serialization, Deserialization and Parsing inData Serialization, Deserialization and Parsing in
Rust CLIsRust CLIs
TheThe  crate crateserdeserde
TheThe  book bookserdeserde
We will write a command line application in Rust.
 
It will base64 decode a json web token to standard output
Use statements Library Dependencies
Here are 3 Structs and notice that the Token struct has both
the Header and Claims struct embedded in it.
The new methods for the Claims and Headers structs
instantiate a new Claims and Header instance.
Here is the main program.Here is the main program.
Demo!!!Demo!!!
Having some ascii fun now in the command line
Having some ascii fun now in the command line
This C program generates ascii characters to standard output.
./ascii_table | sed "s;.;'&',;g" | pbcopy
This shell command replaces the output with double quotes and a
comma and copies standard output to system clipboard
The main rust program just prints some ascii characters to
standard output for fun!!
Time to shred some web scraping waves!!Time to shred some web scraping waves!!
Here are our dependencies for the Web Scraping project:
Here is our use and crate statements:
Here is the main logic for the Web Scraping Project
Here is the main function:
Notice that we ran the run() function and wrap it in a `if let`
statement which will print error and exit if there is an error.
Demo!!Demo!!
Debugging Rust ApplicationsDebugging Rust Applications
Printing values with println! macro in RustPrinting values with println! macro in Rust
Printing with named value
Pretty Print with println("{:#?}", something);
Debugging Rust applications with rust-lldb.
There are 2 debuggers that come prebundled with cargo:
rust-lldb
rust-gdb
If you are working on Mac OS X it is easier to use rust-lldb
You can use gdb in Mac OS X but it requires extra steps:
First install gdb, easiest way is via homebrew package manager
Next you will need to codesign gdb, if you are interested follow
the steps in this CODESIGN-GIST
For the purposes of this demo we will use rust-lldb
Here we start rust-lldb using the compiled binary executable
Notice here that we run the main.rs file by issuing the command run
Let us set a breakpoint in lldb
This is the short form version of setting a breakpoint
This is the longer but more powerful way to set breakpoint
Let us run our program with breakpoint set
Notice here that lldb stopped in line 6 which is our breakpoint!
We issued command "frame variable args" to see variable
Note that the commands for printing: p (simple types), po
(objects), and pa (arrays) don't work as well with Rust.
The frame command is used to examine current stack frame and
has various subcommands such as variable which work better!
Step over with lldb
Resume/Continue execution of program
Notice here that we continued until the next breakpoint!
List breakpoints
Delete all breakpoints
Delete specific breakpoint(s)
First do Instruction level single step, stepping over calls
Next actually step into function
Next let us step over and then print value of variable
Step out of the function
Get stack frame information and continue execution
Use expression to set values in running program
Print back trace information
Kill lldb session
Questions?Questions?
How to find me:How to find me:
@ Github@ Githubjbelmontjbelmont
@ Twitter@ Twitterjbelmont80jbelmont80
Personal website @Personal website @ marcelbelmont.commarcelbelmont.com
@ LinkedIn@ LinkedInJean-Marcel BelmontJean-Marcel Belmont
Checkout my new book titled Hands On Continuous
Integration with Jenkins, Travis, and Circle CI

More Related Content

What's hot (20)

PDF
KubeCon EU 2016: Leveraging ephemeral namespaces in a CI/CD pipeline
KubeAcademy
 
PPTX
Where is my scalable API?
Juan Pablo Genovese
 
PDF
Vagrant - the essence of DevOps in a tool
Paul Stack
 
PDF
KubeCon EU 2016: Getting the Jobs Done With Kubernetes
KubeAcademy
 
PDF
Dev ops with smell v1.2
Antons Kranga
 
PDF
An Introduction to Rancher
Conner Swann
 
PDF
Monitoring kubernetes with prometheus
Brice Fernandes
 
PDF
Serverless, Tekton, and Argo CD: How to craft modern CI/CD workflows | DevNat...
Red Hat Developers
 
PDF
Making Spinnaker Go @ Stitch Fix
Diana Tkachenko
 
PDF
Microservices: 5 things I wish I'd known - Vincent Kok - Codemotion Amsterdam...
Codemotion
 
PPTX
Airflow Clustering and High Availability
Robert Sanders
 
PDF
DevOps Summit 2016 - The immutable Journey
smalltown
 
PPTX
Automated testing on steroids – Trick for managing test data using Docker sna...
Lucas Jellema
 
PDF
Simon Laws – Apache Flink Cluster Deployment on Docker and Docker-Compose
Flink Forward
 
PPTX
Integration testing for salt states using aws ec2 container service
SaltStack
 
PDF
Gitlab and Lingvokot
Lingvokot
 
PDF
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
Docker, Inc.
 
PDF
Securing Containers, One Patch at a Time - Michael Crosby, Docker
Docker, Inc.
 
PDF
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
Puppet
 
PDF
Automate CI/CD with Rancher
Nick Thomas
 
KubeCon EU 2016: Leveraging ephemeral namespaces in a CI/CD pipeline
KubeAcademy
 
Where is my scalable API?
Juan Pablo Genovese
 
Vagrant - the essence of DevOps in a tool
Paul Stack
 
KubeCon EU 2016: Getting the Jobs Done With Kubernetes
KubeAcademy
 
Dev ops with smell v1.2
Antons Kranga
 
An Introduction to Rancher
Conner Swann
 
Monitoring kubernetes with prometheus
Brice Fernandes
 
Serverless, Tekton, and Argo CD: How to craft modern CI/CD workflows | DevNat...
Red Hat Developers
 
Making Spinnaker Go @ Stitch Fix
Diana Tkachenko
 
Microservices: 5 things I wish I'd known - Vincent Kok - Codemotion Amsterdam...
Codemotion
 
Airflow Clustering and High Availability
Robert Sanders
 
DevOps Summit 2016 - The immutable Journey
smalltown
 
Automated testing on steroids – Trick for managing test data using Docker sna...
Lucas Jellema
 
Simon Laws – Apache Flink Cluster Deployment on Docker and Docker-Compose
Flink Forward
 
Integration testing for salt states using aws ec2 container service
SaltStack
 
Gitlab and Lingvokot
Lingvokot
 
From Arm to Z: Building, Shipping, and Running a Multi-platform Docker Swarm ...
Docker, Inc.
 
Securing Containers, One Patch at a Time - Michael Crosby, Docker
Docker, Inc.
 
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
Puppet
 
Automate CI/CD with Rancher
Nick Thomas
 

Similar to Writing Rust Command Line Applications (20)

PDF
Making CLI app in ruby
Huy Do
 
PPTX
MozillaPH Rust Hack & Learn Session 1
Robert 'Bob' Reyes
 
PDF
Building Awesome CLI apps in Go
Steven Francia
 
PDF
Interface Oxidation
Ovidiu Farauanu
 
PPTX
Pyconke2018
kent marete
 
PPTX
A Slice Of Rust - A quick look at the Rust programming language
LloydMoore
 
PPTX
Rustbridge
kent marete
 
PDF
Golang workshop
Victor S. Recio
 
PDF
Rust in Action Systems programming concepts and techniques 1st Edition Tim Mc...
paaolablan
 
PDF
Rust All Hands Winter 2011
Patrick Walton
 
PPTX
Introduction to Rust (Presentation).pptx
Knoldus Inc.
 
PDF
Rust Web Development With warp tokio and reqwest 1st Edition Bastian Gruber
fetsertjelta
 
PDF
The Rust Programming Language Steve Klabnik
nmiriorola
 
PDF
Learning Rust By Building Small CLI Tools!.pdf
Jim Lynch
 
PDF
Rusted Ruby
Ian Pointer
 
PDF
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
apidays
 
PDF
Rust for professionals.pdf
ssuser16d801
 
KEY
Introducing Command Line Applications with Ruby
Nikhil Mungel
 
PPTX
From NodeJS to Rust
Bastian Gruber
 
PDF
Building Command Line Tools with Golang
Takaaki Mizuno
 
Making CLI app in ruby
Huy Do
 
MozillaPH Rust Hack & Learn Session 1
Robert 'Bob' Reyes
 
Building Awesome CLI apps in Go
Steven Francia
 
Interface Oxidation
Ovidiu Farauanu
 
Pyconke2018
kent marete
 
A Slice Of Rust - A quick look at the Rust programming language
LloydMoore
 
Rustbridge
kent marete
 
Golang workshop
Victor S. Recio
 
Rust in Action Systems programming concepts and techniques 1st Edition Tim Mc...
paaolablan
 
Rust All Hands Winter 2011
Patrick Walton
 
Introduction to Rust (Presentation).pptx
Knoldus Inc.
 
Rust Web Development With warp tokio and reqwest 1st Edition Bastian Gruber
fetsertjelta
 
The Rust Programming Language Steve Klabnik
nmiriorola
 
Learning Rust By Building Small CLI Tools!.pdf
Jim Lynch
 
Rusted Ruby
Ian Pointer
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
apidays
 
Rust for professionals.pdf
ssuser16d801
 
Introducing Command Line Applications with Ruby
Nikhil Mungel
 
From NodeJS to Rust
Bastian Gruber
 
Building Command Line Tools with Golang
Takaaki Mizuno
 
Ad

More from All Things Open (20)

PDF
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
PPTX
Big Data on a Small Budget: Scalable Data Visualization for the Rest of Us - ...
All Things Open
 
PDF
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
PDF
Let's Create a GitHub Copilot Extension! - Nick Taylor, Pomerium
All Things Open
 
PDF
Leveraging Pre-Trained Transformer Models for Protein Function Prediction - T...
All Things Open
 
PDF
Gen AI: AI Agents - Making LLMs work together in an organized way - Brent Las...
All Things Open
 
PDF
You Don't Need an AI Strategy, But You Do Need to Be Strategic About AI - Jes...
All Things Open
 
PPTX
DON’T PANIC: AI IS COMING – The Hitchhiker’s Guide to AI - Mark Hinkle, Perip...
All Things Open
 
PDF
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...
All Things Open
 
PDF
Leveraging Knowledge Graphs for RAG: A Smarter Approach to Contextual AI Appl...
All Things Open
 
PPTX
Artificial Intelligence Needs Community Intelligence - Sriram Raghavan, IBM R...
All Things Open
 
PDF
Don't just talk to AI, do more with AI: how to improve productivity with AI a...
All Things Open
 
PPTX
Open-Source GenAI vs. Enterprise GenAI: Navigating the Future of AI Innovatio...
All Things Open
 
PDF
The Death of the Browser - Rachel-Lee Nabors, AgentQL
All Things Open
 
PDF
Making Operating System updates fast, easy, and safe
All Things Open
 
PDF
Reshaping the landscape of belonging to transform community
All Things Open
 
PDF
The Unseen, Underappreciated Security Work Your Maintainers May (or may not) ...
All Things Open
 
PDF
Integrating Diversity, Equity, and Inclusion into Product Design
All Things Open
 
PDF
The Open Source Ecosystem for eBPF in Kubernetes
All Things Open
 
PDF
Open Source Privacy-Preserving Metrics - Sarah Gran & Brandon Pitman
All Things Open
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Big Data on a Small Budget: Scalable Data Visualization for the Rest of Us - ...
All Things Open
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Let's Create a GitHub Copilot Extension! - Nick Taylor, Pomerium
All Things Open
 
Leveraging Pre-Trained Transformer Models for Protein Function Prediction - T...
All Things Open
 
Gen AI: AI Agents - Making LLMs work together in an organized way - Brent Las...
All Things Open
 
You Don't Need an AI Strategy, But You Do Need to Be Strategic About AI - Jes...
All Things Open
 
DON’T PANIC: AI IS COMING – The Hitchhiker’s Guide to AI - Mark Hinkle, Perip...
All Things Open
 
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...
All Things Open
 
Leveraging Knowledge Graphs for RAG: A Smarter Approach to Contextual AI Appl...
All Things Open
 
Artificial Intelligence Needs Community Intelligence - Sriram Raghavan, IBM R...
All Things Open
 
Don't just talk to AI, do more with AI: how to improve productivity with AI a...
All Things Open
 
Open-Source GenAI vs. Enterprise GenAI: Navigating the Future of AI Innovatio...
All Things Open
 
The Death of the Browser - Rachel-Lee Nabors, AgentQL
All Things Open
 
Making Operating System updates fast, easy, and safe
All Things Open
 
Reshaping the landscape of belonging to transform community
All Things Open
 
The Unseen, Underappreciated Security Work Your Maintainers May (or may not) ...
All Things Open
 
Integrating Diversity, Equity, and Inclusion into Product Design
All Things Open
 
The Open Source Ecosystem for eBPF in Kubernetes
All Things Open
 
Open Source Privacy-Preserving Metrics - Sarah Gran & Brandon Pitman
All Things Open
 
Ad

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Digital Circuits, important subject in CS
contactparinay1
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 

Writing Rust Command Line Applications

  • 1. Writing Rust CLI ApplicationsWriting Rust CLI Applications Jean-Marcel BelmontJean-Marcel Belmont Senior Software EngineerSenior Software Engineer
  • 2. What is a cli anyway?What is a cli anyway? “ A command-line interface or command language interpreter (CLI), also known as command-line user interface, console user interface[1] and character user interface (CUI), is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines). A program which handles the interface is called a command language interpreter or shell (computing). According to wikipedia:
  • 3. clis are for hackers rightclis are for hackers right
  • 4. Who needs clis I have my IDEWho needs clis I have my IDE I press F5 and boom I am golden!!!I press F5 and boom I am golden!!!
  • 5. Let the CLI Cookoff begin!!Let the CLI Cookoff begin!!
  • 6. CLI program that computes a sum in Rust.CLI program that computes a sum in Rust. Rust has several different ways to iterate through collections!
  • 7. We can use a for in loop with Rust.We can use a for in loop with Rust. Notice that we didn't put a return statement here!Notice that we didn't put a return statement here! sum is an expression and will return.sum is an expression and will return.
  • 8. We can use iterator methods to do the same actionWe can use iterator methods to do the same action foldfold is an iterator method that applies ais an iterator method that applies a function, producing a single, final value.function, producing a single, final value. Notice here that we used the explicit return statement here!Notice here that we used the explicit return statement here! Using the return statement like this is not considered idiomatic.Using the return statement like this is not considered idiomatic.
  • 11. CLI program that computes sum in GolangCLI program that computes sum in Golang
  • 12. Here is a sum function for the Go Program In Go you will typically use a for loop to iterate through collections.
  • 13. Run sum program in go with this commandRun sum program in go with this command Here we pass in our arguments after we run the main.go program Alternatively you can build your program and then run the binary!
  • 15. Making an HTTP RequestMaking an HTTP Request
  • 16. Let us write a Rust Script that makes an HTTP Request Here we use the library to make an HTTP requestreqwest
  • 17. Here is the main programHere is the main program
  • 18. Here I put a sleep so that I could quickly copy theHere I put a sleep so that I could quickly copy the standard output of this command!standard output of this command! The tee command will spit out standard output andThe tee command will spit out standard output and create a file for us in one go.create a file for us in one go.
  • 19. Demo this script!!Demo this script!!
  • 20. Same Program with GolangSame Program with Golang
  • 21. Golang has a standard library that you can use toGolang has a standard library that you can use to make http calls!make http calls! No 3rd Party Libraries neededNo 3rd Party Libraries needed
  • 22. You can use this handy online tool to convert jsonYou can use this handy online tool to convert json schemas into Go Structsschemas into Go Structs
  • 23. Here is the main program that makes an http requestHere is the main program that makes an http request to Travis CI API.to Travis CI API.
  • 24. Here is the rest of the programHere is the rest of the program Notice here that I renamed the Autogenerated Name to ReposNotice here that I renamed the Autogenerated Name to Repos
  • 26. Lets Test our Rust CLILets Test our Rust CLI programs!!programs!!
  • 27. Changing the structure of the summation program for testingChanging the structure of the summation program for testing Here we supply an option ofHere we supply an option of --lib--lib to cargo and it generates ato cargo and it generates a lib.rslib.rs Notice that cargo generated a test for us in a file calledNotice that cargo generated a test for us in a file called lib.rslib.rs
  • 28. We will break apart the 2 summation functions from the main.rs into the lib.rs Notice here that we add pub for public visibility
  • 29. Notice here that we now use our lib as an internal crate! We call our public method with the crate name now.
  • 30. We add the following annotation to create our unit test cases.
  • 31. Now we can unit test our cli program by issuing the cargo test command Notice here that both of our unit test cases run when we run cargo test!
  • 32. Demo Building average cli program!Demo Building average cli program!
  • 34. Let us unit test our summer cli programLet us unit test our summer cli program We simply create a file withWe simply create a file with _test.go_test.go to writeto write tests in Golangtests in Golang
  • 35. We import the testing package into main_test.goWe import the testing package into main_test.go Notice here that we assert numbers should not equal 12.0.Notice here that we assert numbers should not equal 12.0.
  • 36. Let us run the Go Test fileLet us run the Go Test file
  • 37. Hacking with the Rust clap libraryHacking with the Rust clap library
  • 38. Using Clap to build Robust Clis in Rust Clap has many features to build robust features
  • 39. Using Clap to build Robust Clis in Rust let matches = App::new("Calculator") .subcommand(SubCommand::with_name("add") .about("Sum some numbers") .version("0.1") .author("Jean-Marcel Belmont") .arg(Arg::with_name("numbers") .multiple(true) .help("the numbers to add") .required(true))) .subcommand(SubCommand::with_name("subtract") .about("Subtract some numbers") .version("0.1") .author("Jean-Marcel Belmont") .arg(Arg::with_name("numbers") .multiple(true) .help("the numbers to subtract") .index(1) .required(true))) Here we use subcommands to build a calculator cli application
  • 40. Here we run the binary executable to run our simple calculator cli application Notice that each subcommand performs a different calculation. Also notice that we are using the binary executable here.   It is created upon successful `cargo run` and/or `cargo build`.
  • 42. Let us look at the cobraLet us look at the cobra
  • 43. No not the movie Cobra with Slyvester Stallone!No not the movie Cobra with Slyvester Stallone! Let us look at the Golang CLI Library.Let us look at the Golang CLI Library.
  • 44. Here we create a cli application with cobra init command! We then create a symbolic link to it in this directory Here we initialize a cobra yaml file for common info! Now we finally create our main calculator logic.
  • 45. Here is bulk of the logic for add, subtract, multiply, and divide We have a cobra.Command and supply our function to run!
  • 46. The first command runs the add subcommand. The second command builds the binary executable. The third command runs the binary executable and runs the subtract subcommand. Each command afterwards is demonstrating the other subcommands in the calculator program.
  • 48. Let's Check off parsing, serialization, andLet's Check off parsing, serialization, and deserialization of our Rust Bucket List Nextdeserialization of our Rust Bucket List Next
  • 49. Data Serialization, Deserialization and Parsing inData Serialization, Deserialization and Parsing in Rust CLIsRust CLIs TheThe  crate crateserdeserde TheThe  book bookserdeserde
  • 50. We will write a command line application in Rust.   It will base64 decode a json web token to standard output Use statements Library Dependencies
  • 51. Here are 3 Structs and notice that the Token struct has both the Header and Claims struct embedded in it. The new methods for the Claims and Headers structs instantiate a new Claims and Header instance.
  • 52. Here is the main program.Here is the main program.
  • 54. Having some ascii fun now in the command line
  • 55. Having some ascii fun now in the command line This C program generates ascii characters to standard output. ./ascii_table | sed "s;.;'&',;g" | pbcopy This shell command replaces the output with double quotes and a comma and copies standard output to system clipboard
  • 56. The main rust program just prints some ascii characters to standard output for fun!!
  • 57. Time to shred some web scraping waves!!Time to shred some web scraping waves!!
  • 58. Here are our dependencies for the Web Scraping project: Here is our use and crate statements:
  • 59. Here is the main logic for the Web Scraping Project
  • 60. Here is the main function: Notice that we ran the run() function and wrap it in a `if let` statement which will print error and exit if there is an error.
  • 63. Printing values with println! macro in RustPrinting values with println! macro in Rust
  • 64. Printing with named value Pretty Print with println("{:#?}", something);
  • 65. Debugging Rust applications with rust-lldb. There are 2 debuggers that come prebundled with cargo: rust-lldb rust-gdb If you are working on Mac OS X it is easier to use rust-lldb You can use gdb in Mac OS X but it requires extra steps: First install gdb, easiest way is via homebrew package manager Next you will need to codesign gdb, if you are interested follow the steps in this CODESIGN-GIST
  • 66. For the purposes of this demo we will use rust-lldb Here we start rust-lldb using the compiled binary executable Notice here that we run the main.rs file by issuing the command run
  • 67. Let us set a breakpoint in lldb This is the short form version of setting a breakpoint This is the longer but more powerful way to set breakpoint
  • 68. Let us run our program with breakpoint set Notice here that lldb stopped in line 6 which is our breakpoint! We issued command "frame variable args" to see variable Note that the commands for printing: p (simple types), po (objects), and pa (arrays) don't work as well with Rust. The frame command is used to examine current stack frame and has various subcommands such as variable which work better!
  • 69. Step over with lldb Resume/Continue execution of program Notice here that we continued until the next breakpoint!
  • 70. List breakpoints Delete all breakpoints Delete specific breakpoint(s)
  • 71. First do Instruction level single step, stepping over calls Next actually step into function
  • 72. Next let us step over and then print value of variable Step out of the function
  • 73. Get stack frame information and continue execution Use expression to set values in running program
  • 74. Print back trace information Kill lldb session
  • 76. How to find me:How to find me: @ Github@ Githubjbelmontjbelmont @ Twitter@ Twitterjbelmont80jbelmont80 Personal website @Personal website @ marcelbelmont.commarcelbelmont.com @ LinkedIn@ LinkedInJean-Marcel BelmontJean-Marcel Belmont Checkout my new book titled Hands On Continuous Integration with Jenkins, Travis, and Circle CI