1 The Problem
We want a small program that converts a temperature from Celsius to Fahrenheit, or the other way around. The user picks which direction, types a number, and the program does the maths and shows the answer. Simple — but it teaches the core shape of every calculator-style tool: ask, calculate, show.
2 How to Think About It
Before any code, think about the two things the program needs to know and the two formulas it might use. You do not need Go yet — just the plan:
3 The Build — explained part by part
Here is the complete converter. Read each part’s note below — you should understand the whole thing from the notes alone.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// cToF converts Celsius to Fahrenheit.
func cToF(celsius float64) float64 {
return celsius*9/5 + 32
}
// fToC converts Fahrenheit to Celsius.
func fToC(fahrenheit float64) float64 {
return (fahrenheit - 32) * 5 / 9
}
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Temperature Converter")
fmt.Println("1. Celsius to Fahrenheit")
fmt.Println("2. Fahrenheit to Celsius")
fmt.Print("Choose 1 or 2: ")
choiceLine, _ := reader.ReadString('\n')
choice := strings.TrimSpace(choiceLine)
switch choice {
case "1":
fmt.Print("Enter temperature in Celsius: ")
line, _ := reader.ReadString('\n')
celsius, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
if err != nil {
fmt.Println("Please type a number.")
return
}
fmt.Printf("%.1f°C is %.1f°F\n", celsius, cToF(celsius))
case "2":
fmt.Print("Enter temperature in Fahrenheit: ")
line, _ := reader.ReadString('\n')
fahrenheit, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
if err != nil {
fmt.Println("Please type a number.")
return
}
fmt.Printf("%.1f°F is %.1f°C\n", fahrenheit, fToC(fahrenheit))
default:
fmt.Println("Please choose 1 or 2.")
}
}
switch choice { case "1": ... } — Go’s
switch is the natural way to branch on several exact values. It plays the same role as Python’s if / elif / else chain, but reads more like a menu.strconv.ParseFloat(strings.TrimSpace(line), 64) — turn the typed text into a decimal number. We use
ParseFloat (not Atoi) because temperatures can have decimals like 36.6; the 64 means “give me a 64-bit float”, Go’s standard precision.celsius*9/5 + 32 — the formula. Go follows normal maths order too: multiply and divide first, then add — identical to the Python version.
fmt.Printf("%.1f°C is %.1f°F\n", ...) —
%.1f means “a decimal number rounded to 1 place”. Go does not auto-print floats the way Python’s f-strings do, so you choose the format explicitly — which also means you control it precisely.
celsius as an int instead of float64 — then 36.6 degrees loses its decimal, and integer division truncates the formula too.float64 for anything that can have a decimal, like temperature.celsius * 9 / 5 + 32 but expecting celsius * (9 / 5 + 32).strings.TrimSpace before comparing choice to "1" — the trailing newline from ReadString means it never matches.ReadString('\n') before comparing or converting it.4 Test & Prove Each Part
How do we know the formulas are right? We test them against temperatures we already know — water freezes at 0°C / 32°F and boils at 100°C / 212°F. If those come out right, the formula is right.
package main
import "testing"
func TestFreezingPoint(t *testing.T) {
if got := cToF(0); got != 32 {
t.Errorf("cToF(0) = %v; want 32", got)
}
}
func TestBoilingPoint(t *testing.T) {
if got := cToF(100); got != 212 {
t.Errorf("cToF(100) = %v; want 212", got)
}
}
func TestReverseFreezing(t *testing.T) {
if got := fToC(32); got != 0 {
t.Errorf("fToC(32) = %v; want 0", got)
}
}
func TestRoundTrip(t *testing.T) {
got := fToC(cToF(25))
if got < 24.99999 || got > 25.00001 {
t.Errorf("round trip through both formulas = %v; want ~25", got)
}
}
Run with go test -v ./.... We pulled the formulas into small functions (cToF, fToC) so the tests can call them directly, without any menu or typed input in the way. Testing against known facts — freezing and boiling points — is a powerful way to trust your maths, in any language.
5 The Interface
The program’s interface — what it asks for and what it gives back — documented plainly.
What it expects
Choose 1 or 2: 1
Enter temperature in Celsius: 100What it returns
100.0°C is 212.0°F6 Run It & Automate It
Save the code as converter.go and run it with go run converter.go — Go compiles and executes in one step, no separate build needed while you are experimenting.
go run converter.goPick a direction, type a temperature, and see the conversion.
A CI tool like Jenkins runs go test automatically whenever the code changes — every line below has a plain explanation.
Temperature Converter
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Choose 1 or 2: 1
Enter temperature in Celsius: 100
100.0°C is 212.0°F25 or 36.6.strings.TrimSpace before the switch. The trailing newline from typing Enter must be trimmed first.// Jenkinsfile — runs the tests automatically every time the code changes.
pipeline {
agent any // run on any available machine
stages {
stage('Get the code') {
steps { checkout scm } // download the latest code
}
stage('Set up Go') {
steps {
sh 'go version' // confirm Go is installed
sh 'test -f go.mod || go mod init temperature_converter' // create a module if none exists
}
}
stage('Run the tests') {
steps {
sh 'go vet ./...' // catch obvious mistakes before running
sh 'go test -v ./...' // run every test, show each result
}
}
}
post {
success { echo 'All tests passed.' }
failure { echo 'A test failed — look above.' }
}
}
You have a working converter. Extend it:
- Add Kelvin. Offer Celsius→Kelvin too (Kelvin = Celsius + 273.15). (Teaches: more
casebranches.) - Round differently. Try
%.0ffor a whole-number answer, or%.2ffor more precision. (Teaches: format verbs.) - Keep converting. Wrap the whole thing in a
forloop so the user can do many conversions without restarting. (Teaches: an outer loop.) - Guard bad input harder. Instead of quitting on a bad number, loop back and ask again. (Teaches: retry logic.)
float64 and strconv.ParseFloat for decimals, switch for choices, and how to test maths against known facts with go test. Related reference: Variables & Types, Control Flow.