You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Go is not an object-oriented language in the traditional sense — it has no classes, no inheritance, and no constructors. Instead, Go uses structs to group data and methods to add behaviour to types. This approach is simpler than class-based OOP while remaining powerful and flexible.
A struct is a composite type that groups named fields:
type User struct {
ID int
Name string
Email string
Active bool
CreatedAt time.Time
}
// Named fields (recommended)
u := User{
ID: 1,
Name: "Alice",
Email: "alice@example.com",
Active: true,
}
// Positional (fragile — not recommended)
u := User{1, "Alice", "alice@example.com", true, time.Now()}
// Zero-value struct
var u User // all fields set to zero values
fmt.Println(u.Name) // Alice
u.Active = false // modify a field
Struct tags are metadata attached to fields, commonly used for JSON encoding, database mapping, and validation:
type User struct {
ID int `json:"id" db:"user_id"`
Name string `json:"name" db:"user_name"`
Email string `json:"email,omitempty"`
}
| Tag | Purpose |
|---|---|
json:"name" | JSON field name |
json:",omitempty" | Omit field if zero value |
json:"-" | Exclude from JSON |
db:"column_name" | Database column name |
validate:"required" | Validation rules |
u := User{ID: 1, Name: "Alice"}
data, _ := json.Marshal(u)
fmt.Println(string(data))
// {"id":1,"name":"Alice"}
A method is a function with a receiver — it belongs to a specific type:
func (u User) FullName() string {
return u.Name
}
// Usage:
u := User{Name: "Alice"}
fmt.Println(u.FullName()) // Alice
| Receiver | Syntax | Can Modify? | Copy? |
|---|---|---|---|
| Value | func (u User) | No | Works on a copy |
| Pointer | func (u *User) | Yes | Works on the original |
// Value receiver — cannot modify u
func (u User) Greeting() string {
return "Hello, " + u.Name
}
// Pointer receiver — can modify u
func (u *User) Deactivate() {
u.Active = false
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.