Go for Rubysts
Thiago Pradi
RubyConf Argentina - 2013
whoami
•

Thiago Pradi

•

Brazilian!

•

Software Developer @ JobScore

•

Bachelor of Computer Science @ FURB

•

Octopu...
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)

•

Deve...
Go is an open source
programming environment
that makes it easy to build
simple, reliable, and
efficient software.
Source: ...
Features
•

New

•

Concurrent

•

Compiled

•

Garbaged-collected

•

Simple & Fun!
Language focus
•

System programming

•

Networked / multi-core

•

Fast

•

Compatible with C

•

Best of static typed la...
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 / ru...
Organizing code
package string_processing;



func Process(str string) {

// Code code code
	
}

package main	


import "s...
Workspace
•

The default way to organize code in Go

•

Build to work with OpenSource repositories

•

Directories src, bi...
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

•

Every...
class Animal	
attr_accessor :name	
	
def initialize(name)	
self.name = name	
end	
	
def say_something	
puts "HEY HEY"	
end...
Objects in Go
•

No inheritance

•

Data types to define content

•

Methods define the operations

•

Interfaces define the ...
package main	
import "fmt"	
type Animal struct {	
Name string 	
}	
!

func (a *Animal) SaySomething() {	
fmt.Println("HEY ...
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 ...
file = File.open("/tmp/mel.txt", "w")	
!

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

No exceptions

•

Errors should implement “Error” interface

•

Erros should be returned as additio...
Off-topic: Gambiarra
func main() {	
fmt.Println("Starting MEL server")	
!

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

if err != nil...
defer / panic / recover
•

Defer is compared to “ensure” in ruby

•

Panic / recover are similar to exception, but
only sh...
func EchoFunction(connection net.Conn, ss
*command_parser.ServerStorage) {	
defer connection.Close()	
!

buf := make([]byt...
func main() {	
PanicFunction()	
fmt.Println("This will not be printed")	
}	
!

func PanicFunction() {	
defer func() {	
fmt...
func main() {	
PanicFunction()	
fmt.Println("This will be printed")	
}	
!

func PanicFunction() {	
defer func() {	
if e :=...
Concurrency

•

Ruby -> Threads / Fibers / EventPool / Actors

•

Go -> Goroutines
Concurrency - Ruby
•

Threads (with shared memory)

•

Fibers

•

EventMachine (Event loop / Reactor pattern)

•

Celluloi...
require 'net/http'	
!

content = []	
!

thread = Thread.new do 	
uri = URI("http://triremi.com/")	
content << Net::HTTP.ge...
Concurrency - Go
•

Goroutines!

•

Lightweight thread implementation

•

Communications between goroutines using
channels...
for {	
connection, err := listener.Accept()	
!

if err != nil {	
fmt.Println("Error accepting the
socket")	
os.Exit(2)	
}	...
for {	
connection, err := listener.Accept()	
!

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

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

go PingFunction(messages)	
!

msg := <-messages	
!

fmt....
// Make the channel with the number of
connections	
channels := make(chan ChannelResult,
number_of_connections)	
!

// Sta...
Testing
•

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

•

Go also has a default framework for te...
Testing in Ruby
•

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

•

Frameworks with lots of assertions and pred...
require "spec_helper"	
!

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

Light framework with the language, with a few
new options

•

Don’t come with assertions / macros

•

Tes...
package command_parser;	
!

import ( “testing" )	
!

func Test_parseSetCommand (t *testing.T) {	
ss := new(ServerStorage)	...
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/doc...
Mine
•

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

•

Brainfuck compiler (https://github.com/
...
Wrapping up…
•

Cool language

•

Concurrent and networked

•

Benefits from both dynamic and static
languages

•

Modern

...
One more thing..
GOLang!
GOLang!
Thank you!
•

www.thiagopradi.net

•

twitter.com/thiagopradi

•

thiago.pradi@gmail.com
Go for Rubyists
Go for Rubyists
Upcoming SlideShare
Loading in …5
×

Go for Rubyists

1,926 views
1,767 views

Published on

This presentation tries to introduce people that are familiar to ruby with Go.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,926
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
23
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Go for Rubyists

  1. 1. Go for Rubysts Thiago Pradi RubyConf Argentina - 2013
  2. 2. whoami • Thiago Pradi • Brazilian! • Software Developer @ JobScore • Bachelor of Computer Science @ FURB • Octopus author / maintainer
  3. 3. Thiago was a happy Ruby developer...
  4. 4. that wanted to learn something new!
  5. 5. Why not a new language? ... ... Maybe Go!
  6. 6. Google trends - Golang
  7. 7. What is Go?
  8. 8. 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!)
  9. 9. Go is an open source programming environment that makes it easy to build simple, reliable, and efficient software. Source: golang.org
  10. 10. Features • New • Concurrent • Compiled • Garbaged-collected • Simple & Fun!
  11. 11. Language focus • System programming • Networked / multi-core • Fast • Compatible with C • Best of static typed language and dynamic languages
  12. 12. Basic Concepts
  13. 13. package main
 
 import "fmt" 
 
 func main() {
 fmt.Println("Hello World")
 }

  14. 14. C-Like Syntax func main() {
 fmt.Printf("Animal with name %s and age %d", "Anaconda", 32)
 }

  15. 15. Compiled language
  16. 16. Typesystem
  17. 17. Strong types func main() { var str string var value int str = "abc" value = 123 str + value }
  18. 18. Static Typed // types.go func main() {
 var a string
 
 a = 123
 }
  19. 19. with dynamic casting package main
 import ( "fmt" )
 
 func main() {
 a := 123
 fmt.Printf("Value of a: %d", a)
 }

  20. 20. User defined types package main;
 
 type Animal struct {
 Name string
 Age int
 }
 
 func main() {
 var anaconda Animal
 }

  21. 21. Compiler • Uses GCC as back end • Checks for unused packages and variables • Checks types and return values
  22. 22. 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
  23. 23. Organizing code package string_processing;
 
 func Process(str string) {
 // Code code code }
 package main 
 import "string_processing"
 func main() {
 string_processing.Process("foobar")
 }
  24. 24. Workspace • The default way to organize code in Go • Build to work with OpenSource repositories • Directories src, bin and pkg
  25. 25. Encoding • Source code: UTF-8 • Strings: UTF-8
  26. 26. Comparing it to Ruby..
  27. 27. Disclaimer
  28. 28. Object Orientation • Ruby uses classes / methods • Golang uses Interfaces, adding methods to data structures.
  29. 29. Objects in Ruby • Ruby Object model • Module / Class with methods • Support for inheritance and composition • Everything is an object
  30. 30. 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
  31. 31. Objects in Go • No inheritance • Data types to define content • Methods define the operations • Interfaces define the behavior of the “object” (data type)
  32. 32. 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() }
  33. 33. Error Handling • Ruby uses Exceptions, with begin / rescue / ensure • Golang use return values with error code (!!!)
  34. 34. Error handling - Ruby • Errors inherit from Exception class • Flow control with begin / rescue / ensure • Don’t need to treat every exception
  35. 35. file = File.open("/tmp/mel.txt", "w") ! begin # does some file processing rescue puts "Failed to process" ensure file.close end
  36. 36. 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”)
  37. 37. Off-topic: Gambiarra
  38. 38. 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) } }
  39. 39. 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
  40. 40. func EchoFunction(connection net.Conn, ss *command_parser.ServerStorage) { defer connection.Close() ! buf := make([]byte, 1024) n, err := connection.Read(buf) // Heavy logic }
  41. 41. 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") }
  42. 42. 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") }
  43. 43. Concurrency • Ruby -> Threads / Fibers / EventPool / Actors • Go -> Goroutines
  44. 44. Concurrency - Ruby • Threads (with shared memory) • Fibers • EventMachine (Event loop / Reactor pattern) • Celluloid (Actor based)
  45. 45. require 'net/http' ! content = [] ! thread = Thread.new do uri = URI("http://triremi.com/") content << Net::HTTP.get(uri) end ! thread.join
  46. 46. Concurrency - Go • Goroutines! • Lightweight thread implementation • Communications between goroutines using channels • Managed by the Go Scheduler • Mapped to a few different OS processes
  47. 47. for { connection, err := listener.Accept() ! if err != nil { fmt.Println("Error accepting the socket") os.Exit(2) } ! EchoFunction(connection, ss) }
  48. 48. for { connection, err := listener.Accept() ! if err != nil { fmt.Println("Error accepting the socket") os.Exit(2) } ! go EchoFunction(connection, ss) }
  49. 49. import "fmt" ! func main() { messages := make(chan string) ! go PingFunction(messages) ! msg := <-messages ! fmt.Println(msg) } ! func PingFunction(messages chan string) { messages <- "ping" }
  50. 50. // 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 }
  51. 51. 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
  52. 52. 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?)
  53. 53. 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
  54. 54. 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
  55. 55. 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") } } }
  56. 56. But, what about some real use cases?
  57. 57. Companies • Google (dl.google.com, youtube) • SoundCloud • Heroku • CloudFlare • Ubuntu
  58. 58. 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
  59. 59. 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)
  60. 60. Wrapping up… • Cool language • Concurrent and networked • Benefits from both dynamic and static languages • Modern • Give it a try!
  61. 61. One more thing..
  62. 62. GOLang!
  63. 63. GOLang!
  64. 64. Thank you! • www.thiagopradi.net • twitter.com/thiagopradi • thiago.pradi@gmail.com

×