Java to Go

7 things to keep in mind when switching from Java to Go

Photo by Patrick Ward on Unsplash

1. Setup is simple; the language is even simpler

package mainimport "fmt"func main() {
fmt.Println("Hello, World!")
}

2. Creating projects is simple

project/                 # project folder
\_ cmd/ # keep the 'main' files here (optional)
|_ examples/ # show how functions/features are used
|_ internal/ # keep private modules here (internal libs)
|_ .gitignore # tells Git what not to stage for commits
|_ .makefile # used to simplify and run Go commands
|_ go.mod # specify your dependencies here
\_ readme.md # every project needs a readme, right

3. You have Interfaces

package mainimport "fmt"type beverage interface {
name() string
caffeine() int
}
type coffee struct {
shots int
}
type tea struct {}func (c coffee) caffeine() int {
return c.shots * 75
}
func (c coffee) name() string {
return "coffee"
}
func (t tea) caffeine() int {
return 45
}
func (t tea) name() string {
return "tea"
}
func howMuchCaffeine(b beverage) {
fmt.Printf("%s has %d g of caffeine\n", b.name(), b.caffeine())
}
func main() {
c := coffee{shots: 2}
t := tea{}
howMuchCaffeine(c)
howMuchCaffeine(t)
}

4. But you also have Pointers

Pass by value

type Person struct {
name string
}
func changeName(p Person) {
p.name = "Bob"
}
func main() {
person := Person {"Alice"}
changeName(person)
fmt.Println(person) // prints "Alice"
}

Pass by reference

type Person struct {
name string
}
func changeName(p *Person) {
p.name = "Bob"
}
func main() {
person := Person {"Alice"}
changeName(&person)
fmt.Println(person) // prints "Bob"
}

5. Write once, run anywhere. Wait, what?

6. You don’t have Generics and you won’t miss them

7. Publishing your code is simple

💻 software engineer ⛰ outdoors enthusiast 👉 linktr.ee/bgguna

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store