Go by Contrast
Types, structs & the basics
Lesson 1 of 5
What you'll learn
- See how Go's static types and structs map to TS objects and interfaces
- Understand methods attached to structs instead of class bodies
- Get a first feel for value vs pointer semantics
Go is statically typed and compiled, like TypeScript — but the types are the language, not a layer on top that erases at build time. There's no any escape hatch you'll reach for daily, and a Go binary carries no runtime type checker because the compiler already proved everything.
A Go struct is the workhorse for "a bag of named fields." It's closest to a TS interface describing an object shape, except in Go the struct is the concrete type.
type User struct {
Name string
Age int
}
// A method is declared outside the struct, with a receiver.
func (u User) Greet() string {
return "Hi, " + u.Name
}
u := User{Name: "Ada", Age: 36}
fmt.Println(u.Greet())
In TypeScript you'd write the shape and the behavior together, or as a class:
interface User {
name: string;
age: number;
}
function greet(u: User): string {
return "Hi, " + u.name;
}
Methods live next to the type, not inside it
Notice func (u User) Greet(). The (u User) part is the receiver — it's what this is in a JS method, but named explicitly. Go has no classes; you attach methods to any type you define. Capitalization matters too: Name (capital) is exported (public), name (lowercase) is package-private. Visibility is a naming convention, not a keyword.
Value vs pointer, briefly
When you pass u User by value, Go copies the struct. To mutate the original, you take a pointer receiver (u *User) — similar to how objects in JS are passed by reference, except in Go you decide per function whether you want a copy or a shared reference.
Zero values, not undefined
Go has no undefined. Every type has a zero value — "" for strings, 0 for numbers, false for bools, nil for pointers. A freshly declared var u User already has usable, well-defined fields.
The challenge below is a JS model of a Go struct plus a method — the runner executes JavaScript, not Go, so we mimic the shape and receiver in plain JS.
Run it. This models a Go struct with a method whose receiver is passed explicitly, like Go's (u User).
In Go, how is a method connected to the struct it operates on?
Next: how Go handles failure without try/catch.
Saved on this device. Sign in to sync your progress everywhere.