Go language for Java Developers

From a full object-oriented programming language back to basic

Go is like C with a garbage collector. While it is considered a high-level language, the modern concept of object-oriented programming is thrown out of the window. So-called classes in Go is basically equivalent to struct in C because Go has no real class.

Pointers

In Go, there is a pointer like C or C++. The only cool part is that you don’t need to deal with malloc and free. The garbage collector will handle that.

Variable declaration and type inference

Let’s say you want to declare an integer. In Java, you can do by:

1
int abc = 123;

In Go, it will be:

1
var abc int = 123;

or

1
abc := 123; // equivalent to var abc int = 123.

Public and private accessor

In Go, if the first character of a variable or method is in lowercase, that variable or method is private. Otherwise

No class in Go.

But you can still have classes in Go with struct.

Here is an example in Java.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class User {
    private String name
    private int age

    public User(name, age) {
        this.name = name;
        this.age = age;
    }

    public bool isUnderAge() {
        return this.age < 19;
    }
}
1
User user = new User("Foo", 123)

Here is an example in Go.

1
2
3
4
5
6
7
8
type User struct {
    Name string
    Age uint8 // unsigned 8-bit integer
}

func (u *User) IsUnderAge() bool {
    return u.Age < 18
}
1
u := User{Name: "Foo", Age: 123}