CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Structs
- Structs
// Structs allow us to create new types that are bundles of data package main import "fmt" type Point struct { X int Y int } func main() { p1 := Point{1, 2} p2 := Point{0, 0} fmt.Println(p1, p2) }
Different ways to initialize structspackage main import "fmt" type Point struct { X int Y int } func main() { p1 := Point{} p2 := Point{X: 1, Y: 2} p3 := Point{X: 5} fmt.Println(p1, p2, p3) }
Mixed types
package main
import "fmt"
type LabeledPoint struct {
X int
Y int
Label string
}
func main() {
p := LabeledPoint{0, 0, "origin"}
fmt.Println(p)
}
Accessing and Modifying Parameters
package main
import "fmt"
type Point struct {
X int
Y int
}
func main() {
p := Point{112, 42}
fmt.Println(p)
fmt.Println(p.X)
fmt.Println(p.Y)
p.X = 15
p.Y = 112
fmt.Println(p)
}
Calling functions on structs
package main
import (
"fmt"
"math"
)
type Point struct {
X float64
Y float64
}
func distance(p1, p2 Point) float64 {
return math.Hypot((p1.X - p2.X), (p1.Y - p2.Y))
}
func main() {
p1 := Point{0, 3}
p2 := Point{4, 0}
fmt.Println(distance(p1, p2))
}