Classes → Structs
Defining types and behavior
Introduction
In this lesson, you'll learn about classes → structs in Go. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with defining types and behavior.
Go has its own approach to defining types and behavior, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
package main
type Person struct {
Name string
Age int
}
// No constructor — struct literal
// Methods via receivers
func (p Person) Greet() string {
return "Hi, I'm " + p.Name
}
func (p *Person) Birthday() {
p.Age++ // pointer receiver for mutation
}
p := Person{Name: "Alice", Age: 30}
fmt.Println(p.Greet())
p.Birthday()Comparing to Java
Here's how you might have written similar code in Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public String greet() {
return "Hi, I'm " + name;
}
public void birthday() { age++; }
}
Person p = new Person("Alice", 30);
System.out.println(p.greet());You may be used to different syntax or behavior.
Go structs have no constructor — use struct literals
You may be used to different syntax or behavior.
Go methods are defined outside the struct with a receiver
You may be used to different syntax or behavior.
Go has no private — unexported (lowercase) is package-private
You may be used to different syntax or behavior.
Go pointer receiver (*T) for mutation; Java fields mutable by default
Step-by-Step Breakdown
1. No Constructor
Go doesn't have constructors. Initialize with struct literals. Use a New() function by convention for complex initialization.
new Person("Alice", 30)Person{Name: "Alice", Age: 30}
// or by convention: NewPerson("Alice", 30)2. Receiver Methods
Go methods are defined outside the struct with a receiver — like Java methods but explicit about the receiver.
public String greet() { return "Hi, " + name; }func (p Person) Greet() string { return "Hi, " + p.Name }3. Capitalization = Access Control
Go uses capitalization for visibility: Name (capital) is exported (public); name (lowercase) is package-private.
private String name; public String getName()Name string // exported
name string // unexported (package-private)Common Mistakes
When coming from Java, developers often make these mistakes:
- Go structs have no constructor — use struct literals
- Go methods are defined outside the struct with a receiver
- Go has no private — unexported (lowercase) is package-private
Key Takeaways
- No constructors — struct literals or New() function
- Methods use receiver syntax outside the struct
- Capital = exported; lowercase = package-private
- Pointer receiver needed for mutation