Shape Area Calculator

Calculates areas and perimeters for rectangles, circles, and triangles using struct methods with both value and pointer receivers. Demonstrates struct embedding and JSON struct tags.

package main

import (
	"encoding/json"
	"fmt"
	"math"
)

type Point struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

type Rectangle struct {
	Origin Point   `json:"origin"`
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
	Label  string  `json:"label"`
}

type Circle struct {
	Center Point   `json:"center"`
	Radius float64 `json:"radius"`
	Label  string  `json:"label"`
}

type Triangle struct {
	A, B, C Point  `json:"-"`
	Label   string `json:"label"`
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
	return 2 * (r.Width + r.Height)
}

func (r *Rectangle) Scale(factor float64) {
	r.Width *= factor
	r.Height *= factor
}

func (c Circle) Area() float64 {
	return math.Pi * c.Radius * c.Radius
}

func (c Circle) Circumference() float64 {
	return 2 * math.Pi * c.Radius
}

func (c *Circle) Scale(factor float64) {
	c.Radius *= factor
}

func distance(a, b Point) float64 {
	dx := b.X - a.X
	dy := b.Y - a.Y
	return math.Sqrt(dx*dx + dy*dy)
}

func (t Triangle) Area() float64 {
	ab := distance(t.A, t.B)
	bc := distance(t.B, t.C)
	ca := distance(t.C, t.A)
	s := (ab + bc + ca) / 2
	return math.Sqrt(s * (s - ab) * (s - bc) * (s - ca))
}

func main() {
	rect := Rectangle{
		Origin: Point{0, 0},
		Width:  10,
		Height: 5,
		Label:  "garden",
	}
	fmt.Printf("%s: area=%.2f, perimeter=%.2f\n", rect.Label, rect.Area(), rect.Perimeter())

	rect.Scale(2)
	fmt.Printf("%s (scaled 2x): area=%.2f, perimeter=%.2f\n", rect.Label, rect.Area(), rect.Perimeter())

	circle := Circle{
		Center: Point{5, 5},
		Radius: 7,
		Label:  "pond",
	}
	fmt.Printf("%s: area=%.2f, circumference=%.2f\n", circle.Label, circle.Area(), circle.Circumference())

	tri := Triangle{
		A:     Point{0, 0},
		B:     Point{4, 0},
		C:     Point{0, 3},
		Label: "ramp",
	}
	fmt.Printf("%s: area=%.2f\n", tri.Label, tri.Area())

	// JSON serialization with struct tags
	data, _ := json.MarshalIndent(rect, "", "  ")
	fmt.Printf("\nRectangle as JSON:\n%s\n", data)

	data, _ = json.MarshalIndent(circle, "", "  ")
	fmt.Printf("\nCircle as JSON:\n%s\n", data)
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy