SlideShare a Scribd company logo
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...
Go for Rubyists
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
Go for Rubyists
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

More Related Content

PDF
Getting Started with Go
PDF
Painless Data Storage with MongoDB & Go
PDF
Introduction to Programming in Go
PDF
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
PDF
Happy Go Programming Part 1
PDF
Happy Go Programming
PDF
WWX2014 speech : Elliott Stoneham "Tardis go"
PPTX
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Getting Started with Go
Painless Data Storage with MongoDB & Go
Introduction to Programming in Go
Go for Object Oriented Programmers or Object Oriented Programming without Obj...
Happy Go Programming Part 1
Happy Go Programming
WWX2014 speech : Elliott Stoneham "Tardis go"
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)

What's hot (20)

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

Similar to Go for Rubyists (20)

PDF
An Introduction to Go
PDF
Happy Go programing
PDF
Introduction to Google's Go programming language
PDF
Lecture 1 - Overview of Go Language 1.pdf
ODP
Programming Under Linux In Python
PPTX
Go from a PHP Perspective
PPTX
Golang basics for Java developers - Part 1
PPTX
Golang - Overview of Go (golang) Language
PDF
Go for SysAdmins - LISA 2015
PDF
Files and streams
PDF
Inroduction to golang
KEY
Monitoring and Debugging your Live Applications
PPTX
PDF
Go serving: Building server app with go
PPSX
Golang getting started
PDF
Geeks Anonymes - Le langage Go
PDF
Golang for PHP programmers: A practical introduction
PDF
The Ring programming language version 1.8 book - Part 45 of 202
PDF
Coding in GO - GDG SL - NSBM
An Introduction to Go
Happy Go programing
Introduction to Google's Go programming language
Lecture 1 - Overview of Go Language 1.pdf
Programming Under Linux In Python
Go from a PHP Perspective
Golang basics for Java developers - Part 1
Golang - Overview of Go (golang) Language
Go for SysAdmins - LISA 2015
Files and streams
Inroduction to golang
Monitoring and Debugging your Live Applications
Go serving: Building server app with go
Golang getting started
Geeks Anonymes - Le langage Go
Golang for PHP programmers: A practical introduction
The Ring programming language version 1.8 book - Part 45 of 202
Coding in GO - GDG SL - NSBM
Ad

Recently uploaded (20)

PPTX
Spectroscopy.pptx food analysis technology
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPT
Teaching material agriculture food technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
1. Introduction to Computer Programming.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Machine Learning_overview_presentation.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
Spectroscopy.pptx food analysis technology
Group 1 Presentation -Planning and Decision Making .pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
Heart disease approach using modified random forest and particle swarm optimi...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Teaching material agriculture food technology
Spectral efficient network and resource selection model in 5G networks
NewMind AI Weekly Chronicles - August'25-Week II
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Unlocking AI with Model Context Protocol (MCP)
1. Introduction to Computer Programming.pptx
Programs and apps: productivity, graphics, security and other tools
Machine Learning_overview_presentation.pptx
A comparative analysis of optical character recognition models for extracting...
Univ-Connecticut-ChatGPT-Presentaion.pdf
Machine learning based COVID-19 study performance prediction
Digital-Transformation-Roadmap-for-Companies.pptx
A comparative study of natural language inference in Swahili using monolingua...

Go for Rubyists