Structs & Methods
Go’s answer to classes
Section titled “Go’s answer to classes”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).
Defining structs
Section titled “Defining structs”// TypeScript interface + objectinterface User { name: string; age: number;}
const u: User = { name: "Alice", age: 30 };console.log(u.name);// Go structtype User struct { Name string Age int}
u := User{Name: "Alice", Age: 30}fmt.Println(u.Name)Methods on structs
Section titled “Methods on structs”In TypeScript, methods live inside a class. In Go, you attach a method to any type by specifying a receiver before the function name.
class User { constructor( public name: string, public age: number, ) {}
greet(): string { return `Hi, I'm ${this.name}`; }}type User struct { Name string Age int}
// Method with value receiverfunc (u User) Greet() string { return "Hi, I'm " + u.Name}Try it
Section titled “Try it”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 structfunc (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)}Loading Go runtime (first run only, ~8 MB)…