SlideShare una empresa de Scribd logo
1 de 66
Descargar para leer sin conexión
Go for Rubysts
Thiago Pradi
RubyConf Argentina - 2013
whoami
•

Thiago Pradi

•

Brazilian!

•

Software Developer @ JobScore

•

Bachelor of Computer Science @ FURB

•

Octopus author / maintainer
Thiago was a happy
Ruby developer...
that wanted to learn
something new!
Why not a new
language? ...
... Maybe Go!
Google trends - Golang
What is Go?
Go
•

Initially developed at Google

•

Created by Ken Thompson (Unix), Rob Pike
(Plan 9), and Russ Cox (libtask)

•

Development started in 2007

•

First release in 2009 (Fairly new!)
Go is an open source
programming environment
that makes it easy to build
simple, reliable, and
efficient software.
Source: golang.org
Features
•

New

•

Concurrent

•

Compiled

•

Garbaged-collected

•

Simple & Fun!
Language focus
•

System programming

•

Networked / multi-core

•

Fast

•

Compatible with C

•

Best of static typed language and dynamic
languages
Basic Concepts
package main



import "fmt" 



func main() {

fmt.Println("Hello World")

}

C-Like Syntax
func main() {

fmt.Printf("Animal with name %s and age %d",
"Anaconda", 32)

}

Compiled language
Typesystem
Strong types
func main() {	
var str string	
var value int	
str = "abc"	
value = 123	
str + value	
}
Static Typed
// types.go	
func main() {

var a string



a = 123

}
with dynamic casting
package main

import ( "fmt" )



func main() {

a := 123

fmt.Printf("Value of a: %d", a)

}

User defined types
package main;



type Animal struct {

Name string

Age int

}



func main() {

var anaconda Animal

}

Compiler
•

Uses GCC as back end

•

Checks for unused packages and variables

•

Checks types and return values
Go tools
•

go fmt -> format your source code (cool!)

•

go get -> manage and install your
dependencies

•

go build / run -> compile and run your
program

•

go test -> run your tests
Organizing code
package string_processing;



func Process(str string) {

// Code code code
	
}

package main	


import "string_processing"

func main() {

string_processing.Process("foobar")

}
Workspace
•

The default way to organize code in Go

•

Build to work with OpenSource repositories

•

Directories src, bin and pkg
Encoding

•

Source code: UTF-8

•

Strings: UTF-8
Comparing it to Ruby..
Disclaimer
Object Orientation

•

Ruby uses classes / methods

•

Golang uses Interfaces, adding methods to
data structures.
Objects in Ruby
•

Ruby Object model

•

Module / Class with methods

•

Support for inheritance and composition

•

Everything is an object
class Animal	
attr_accessor :name	
	
def initialize(name)	
self.name = name	
end	
	
def say_something	
puts "HEY HEY"	
end	
end	
!

a = Animal.new("Duck")	
a.say_something
Objects in Go
•

No inheritance

•

Data types to define content

•

Methods define the operations

•

Interfaces define the behavior of the
“object” (data type)
package main	
import "fmt"	
type Animal struct {	
Name string 	
}	
!

func (a *Animal) SaySomething() {	
fmt.Println("HEY HEY")	
}	
!

func main() {	
a := new(Animal)	
a.Name = "Duck"	
a.SaySomething()	
}
Error Handling

•

Ruby uses Exceptions, with begin / rescue /
ensure

•

Golang use return values with error code (!!!)
Error handling - Ruby
•

Errors inherit from Exception class

•

Flow control with begin / rescue / ensure

•

Don’t need to treat every exception
file = File.open("/tmp/mel.txt", "w")	
!

begin	
# does some file processing	
rescue	
puts "Failed to process"	
ensure	
file.close	
end
Error Handling - Go
•

No exceptions

•

Errors should implement “Error” interface

•

Erros should be returned as additional value

•

Every error should be treated (unless you want
to do a “Gambiarra”)
Off-topic: Gambiarra
func main() {	
fmt.Println("Starting MEL server")	
!

listener, err := net.Listen("tcp",
"0.0.0.0:2653")	
!

if err != nil {	
fmt.Println("Error starting the server")	
os.Exit(1)	
}	
}
defer / panic / recover
•

Defer is compared to “ensure” in ruby

•

Panic / recover are similar to exception, but
only should be used for internal APIs, never
for external APIs.

•

Panic is used for runtime errors, like array out
of bound
func EchoFunction(connection net.Conn, ss
*command_parser.ServerStorage) {	
defer connection.Close()	
!

buf := make([]byte, 1024)	
n, err := connection.Read(buf)	
// Heavy logic	
}
func main() {	
PanicFunction()	
fmt.Println("This will not be printed")	
}	
!

func PanicFunction() {	
defer func() {	
fmt.Println("Called defer function")	
}()	
	
panic("PANIC PANIC PANIC")	
fmt.Println("This will not be printed")	
}
func main() {	
PanicFunction()	
fmt.Println("This will be printed")	
}	
!

func PanicFunction() {	
defer func() {	
if e := recover(); e != nil {	
fmt.Printf("Recovered from %s n", e)	
}	
}()	
	
panic("PANIC PANIC PANIC")	
fmt.Println("This will not be printed")	
}
Concurrency

•

Ruby -> Threads / Fibers / EventPool / Actors

•

Go -> Goroutines
Concurrency - Ruby
•

Threads (with shared memory)

•

Fibers

•

EventMachine (Event loop / Reactor pattern)

•

Celluloid (Actor based)
require 'net/http'	
!

content = []	
!

thread = Thread.new do 	
uri = URI("http://triremi.com/")	
content << Net::HTTP.get(uri)	
end	
!

thread.join
Concurrency - Go
•

Goroutines!

•

Lightweight thread implementation

•

Communications between goroutines using
channels

•

Managed by the Go Scheduler

•

Mapped to a few different OS processes
for {	
connection, err := listener.Accept()	
!

if err != nil {	
fmt.Println("Error accepting the
socket")	
os.Exit(2)	
}	
!

EchoFunction(connection, ss)	
}
for {	
connection, err := listener.Accept()	
!

if err != nil {	
fmt.Println("Error accepting the
socket")	
os.Exit(2)	
}	
!

go EchoFunction(connection, ss)	
}
import "fmt"	
!

func main() {	
messages := make(chan string)	
!

go PingFunction(messages)	
!

msg := <-messages	
!

fmt.Println(msg)	
}	
!

func PingFunction(messages chan string) {	
messages <- "ping"	
}
// Make the channel with the number of
connections	
channels := make(chan ChannelResult,
number_of_connections)	
!

// Start the request in a new goroutine	
go makeRequest(address, start_byte, end_byte,
out, channels)	
!

//Wait for the result of the goroutine in the
channel	
for(loop_var < number_of_connections) {	
chan_res := <-channels	
// Process the result and save to the file	
}
Testing
•

Ruby has a built in framework (Test::Unit) and
a lot of alternatives

•

Go also has a default framework for testing,
and some early-stages alternatives
Testing in Ruby
•

Lots of frameworks: Test::Unit, rspec, MiniTest,
Bacon…

•

Frameworks with lots of assertions and predefined macros

•

Easy to describe behavior (BDD)

•

Everyone tests.. (RIGHT?)
require "spec_helper"	
!

describe Octopus::Model do	
describe "#using method" do	
it "should return self" do	
User.using(:canada).should
be_a(Octopus::ScopeProxy)	
end	
end	
end
Testing in Go
•

Light framework with the language, with a few
new options

•

Don’t come with assertions / macros

•

Tests have the same package as the
application code

•

Tests stay in the same directory of the
application code
package command_parser;	
!

import ( “testing" )	
!

func Test_parseSetCommand (t *testing.T) {	
ss := new(ServerStorage)	
!

str := ss.ParseCommand("SET thiagopradi
valor")	
!

if ss.Dict["thiagopradi"] != "valor" {	
t.Error("failed to set thiagopradi key")	
}	
}	
}
But, what about some
real use cases?
Companies
•

Google (dl.google.com, youtube)

•

SoundCloud

•

Heroku

•

CloudFlare

•

Ubuntu
Open Source
•

https://github.com/youtube/vitess - Process
and tools for scaling MySQL

•

https://github.com/dotcloud/docker - Open
Source application container engine

•

https://github.com/burke/zeus - Rails
preloader
Mine
•

YADM - Yet another download manager
(https://github.com/tchandy/yadm)

•

Brainfuck compiler (https://github.com/
tchandy/bf_compiler_go)

•

Mel - key-value database (https://github.com/
tchandy/mel)
Wrapping up…
•

Cool language

•

Concurrent and networked

•

Benefits from both dynamic and static
languages

•

Modern

•

Give it a try!
One more thing..
GOLang!
GOLang!
Thank you!
•

www.thiagopradi.net

•

twitter.com/thiagopradi

•

thiago.pradi@gmail.com

Más contenido relacionado

La actualidad más candente

PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 

La actualidad más candente (20)

The Ring programming language version 1.5.1 book - Part 38 of 180
The Ring programming language version 1.5.1 book - Part 38 of 180The Ring programming language version 1.5.1 book - Part 38 of 180
The Ring programming language version 1.5.1 book - Part 38 of 180
 
Practicing Python 3
Practicing Python 3Practicing Python 3
Practicing Python 3
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
State of Python (2010)
State of Python (2010)State of Python (2010)
State of Python (2010)
 
Can you upgrade to Puppet 4.x? (Beginner) Can you upgrade to Puppet 4.x? (Beg...
Can you upgrade to Puppet 4.x? (Beginner) Can you upgrade to Puppet 4.x? (Beg...Can you upgrade to Puppet 4.x? (Beginner) Can you upgrade to Puppet 4.x? (Beg...
Can you upgrade to Puppet 4.x? (Beginner) Can you upgrade to Puppet 4.x? (Beg...
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
 
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
 
Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
 
Triton and symbolic execution on gdb
Triton and symbolic execution on gdbTriton and symbolic execution on gdb
Triton and symbolic execution on gdb
 
0.5mln packets per second with Erlang
0.5mln packets per second with Erlang0.5mln packets per second with Erlang
0.5mln packets per second with Erlang
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Fighting API Compatibility On Fluentd Using "Black Magic"
Fighting API Compatibility On Fluentd Using "Black Magic"Fighting API Compatibility On Fluentd Using "Black Magic"
Fighting API Compatibility On Fluentd Using "Black Magic"
 
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
 

Similar a Go for Rubyists

An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
Cloudflare
 

Similar a Go for Rubyists (20)

An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Happy Go programing
Happy Go programingHappy Go programing
Happy Go programing
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming language
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications
 
Golang
GolangGolang
Golang
 
Golang
GolangGolang
Golang
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
Golang getting started
Golang getting startedGolang getting started
Golang getting started
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Golang for PHP programmers: A practical introduction
Golang for PHP programmers: A practical introductionGolang for PHP programmers: A practical introduction
Golang for PHP programmers: A practical introduction
 
The Ring programming language version 1.8 book - Part 45 of 202
The Ring programming language version 1.8 book - Part 45 of 202The Ring programming language version 1.8 book - Part 45 of 202
The Ring programming language version 1.8 book - Part 45 of 202
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
Golang
GolangGolang
Golang
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Go for Rubyists