Skip to content

Structs & Methods

TypeScript has class, interface, and plain objects. Go has structs — plain data types — and methods — functions attached to a type. There are no classes, no inheritance, no this keyword (Go uses a named receiver instead).

TypeScript
// TypeScript interface + object
interface User {
name: string;
age: number;
}
const u: User = { name: "Alice", age: 30 };
console.log(u.name);
Go
// Go struct
type User struct {
Name string
Age int
}
u := User{Name: "Alice", Age: 30}
fmt.Println(u.Name)

In TypeScript, methods live inside a class. In Go, you attach a method to any type by specifying a receiver before the function name.

TypeScript
class User {
constructor(
public name: string,
public age: number,
) {}
greet(): string {
return `Hi, I'm ${this.name}`;
}
}
Go
type User struct {
Name string
Age int
}
// Method with value receiver
func (u User) Greet() string {
return "Hi, I'm " + u.Name
}
package main
import "fmt"
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
// Pointer receiver — can mutate the struct
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
func main() {
rect := Rectangle{Width: 4, Height: 3}
fmt.Printf("Area: %.1f\n", rect.Area())
fmt.Printf("Perimeter: %.1f\n", rect.Perimeter())
rect.Scale(2)
fmt.Printf("After scaling: %.1f x %.1f\n", rect.Width, rect.Height)
}
What keyword defines a struct in Go?
A pointer receiver should be used when:
What is Go's equivalent of JavaScript's this inside a method?
How does Go achieve code reuse without inheritance?