Go🔧Core Languagebeginner
Structs
Go · Core Language · Run with go run
Explanation
Go uses structs for composite data types. There is no `class` keyword. Methods are defined outside the struct body using a receiver syntax. Structs are value types — assigning one copies it; use a pointer receiver when a method needs to mutate state or the struct is large.
Real-World Scenario
A `User` struct holds name, email, and created-at fields. Methods like `Validate()` and `String()` are attached via receivers, making the type implement interfaces implicitly.
Quick Snippet
snippet.go
type Point struct {
X, Y float64
}
// Value receiver — reads state
func (p Point) Distance() float64 {
return math.Sqrt(p.X*p.X + p.Y*p.Y)
}
// Pointer receiver — mutates state
func (p *Point) Scale(factor float64) {
p.X *= factor
p.Y *= factor
}
p := Point{X: 3, Y: 4}
fmt.Println(p.Distance()) // 5
p.Scale(2)
fmt.Println(p) // {6 8}Full Example
structs.go
// Compile: go run structs.go
// Output:
// distance: 5
// scaled: {6 8}
package main
import (
"fmt"
"math"
)
type Point struct {
X, Y float64
}
// Value receiver — reads state
func (p Point) Distance() float64 {
return math.Sqrt(p.X*p.X + p.Y*p.Y)
}
// Pointer receiver — mutates state
func (p *Point) Scale(factor float64) {
p.X *= factor
p.Y *= factor
}
func main() {
p := Point{X: 3, Y: 4}
fmt.Printf("distance: %g\n", p.Distance())
p.Scale(2)
fmt.Printf("scaled: %v\n", p)
}
Run command
go run structs.go