Translate a Ruby class into Go

Hi,

I’m a Ruby developer and I’d like to know the default Go pattern to convert this basic Ruby code into Go:

class Foo
  attr_reader :bar

  def initialize(bar)
    @bar = bar
  end

  def call
    bar.to_s + ', Hello!!!!'
  end
end

my_object = Foo.new("Bob")
my_object.call # => "Bob, Hello!!!!"

How can we write this, in Go?

Also, if I’m write, in Go there is no classes concept. So instead, we have to use modules, is it right?

I changed the last line of your ruby to:

puts my_object.call # => "Bob, Hello!!!!"

so that there would be some output. I also put it in a file called main.rb. Running it produces:

$ ruby main.rb
Bob, Hello!!!!

I then wrote a roughly equivalent Go program (in main.go):

package main

import "fmt"

type Foo struct {
	bar string
}

func (f Foo) call() string {
	return f.bar + ", Hello!!!!"
}

func main() {
	myObject := Foo{
		bar: "Bob",
	}

	fmt.Println(myObject.call())
}

Running it produces:

$ go run main.go
Bob, Hello!!!!
3 Likes

@nathankerr did a great job translating this, but I do want to mention that as you learn Go more you will want to stop “translating” ruby code and eventually start writing code in a manner more suited to Go. This example is fine, but as a former ruby developer I can definitely tell you that many things you are used to doing in ruby won’t be anything like how I would suggest doing them in Go.

The best way I have found to do this is to stop asking “how do i translate X to Go” and instead asking “What problem does X solve, and how would I solve that problem in Go?”

That said, feel free to post specific ruby examples if you are looking for ideas on what the “go way” is to do something. I found this to be a great way to learning the language as I made the transition.

4 Likes

There are also lots of details in the ruby version that I did not translate to Go. Some of these were:

  • did not define an accessor (attr_reader) for the instance variable bar
  • did not convert bar to a string (since I defined bar to be a string)
  • did not create an initializer (I used a literal instead)

All of these things could be done. But there was no reason to.

1 Like

Also, it’s worth noting that Go OO is based on composition and there’s no class inheritance, so more directly comparable code might be:

module Callable
  attr_reader :bar

  def initialize(bar)
    @bar = bar
  end

  def call
    bar.to_s + ', Hello!!!!'
  end
end

class Foo
  include Callable
end

my_object = Foo.new("Bob")
puts my_object.call # => "Bob, Hello!!!!"

and

package main

import "fmt"

type Callable interface {
	Call() string
}

type Foo struct {
	name string
}

func (f Foo) call() string {
	return f.name + ", Hello!!!!"
}

func main() {
	obj := Foo{
		name: "Bob",
	}
	fmt.Println(obj.call())
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.