Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in Go Using AI

Use an AI assistant to write a Go function, run it, and prove it with Go's built-in table tests. Go needs no extra test library.

In short: say the Go version and “standard library only”, give examples, ask for a table-driven test, run go test and go vet.

Why Go with AI

WHY

Go runs cloud tools and backends at companies like Google and Uber. Docker and Kubernetes are written in Go. The language is small and strict, so AI code is easy to check with go vet and tests.

What you need

WHAT
  • Go: download from go.dev. Check with go version.
  • Built-in tools: go test, go vet and gofmt come with Go.
  • IDE + assistant: VS Code with the Go extension + Copilot or Claude Code, or GoLand with Copilot.

How it flows

1 · Describe the function std lib only, examples 2 · AI writes code read every line 3 · gofmt + go vet clean 4 · Ask for table tests many cases, one loop 5 · go test PASS = keep

Install and set up

HOW
  1. Install Go from go.dev/dl.
  2. Check: go version.
  3. Make a module:
mkdir ifsc && cd ifsc
go mod init ifsc

Step 1 — the prompt

COPY THIS PROMPT

Write a Go package ifsc with IsValid(code string) bool that checks an Indian bank IFSC code: 4 letters, then the digit 0, then 6 letters or digits. Ignore spaces around it and allow lowercase. Standard library only. Example: "SBIN0001234" is valid, "SBIN1001234" is not. Only return the code.

Step 2 — the code (tested here)

ifsc.go
// Package ifsc checks Indian bank IFSC codes. Built with an AI assistant, then tested.
package ifsc

import (
	"regexp"
	"strings"
)

// Format: 4 letters (bank), the digit 0, then 6 letters or digits (branch).
var pattern = regexp.MustCompile(`^[A-Z]{4}0[A-Z0-9]{6}$`)

// IsValid reports whether code looks like a valid IFSC code.
// Spaces around the code are ignored and lowercase is allowed.
func IsValid(code string) bool {
	return pattern.MatchString(strings.ToUpper(strings.TrimSpace(code)))
}

Step 3 — ask for a table test, then run it

FOLLOW-UP PROMPT

Write a table-driven Go test for IsValid with valid, lowercase-with-spaces, wrong 5th character, too short and empty cases.

ifsc_test.go
package ifsc

import "testing"

func TestIsValid(t *testing.T) {
	cases := []struct {
		in   string
		want bool
	}{
		{"SBIN0001234", true},
		{" hdfc0000123 ", true},
		{"SBIN1001234", false}, // 5th char must be 0
		{"SBI0001234", false},  // too short
		{"", false},
	}
	for _, c := range cases {
		if got := IsValid(c.in); got != c.want {
			t.Errorf("IsValid(%q) = %v, want %v", c.in, got, c.want)
		}
	}
}
go vet ./...
go test -v ./...
# -> --- PASS: TestIsValid
# -> ok  ifsc
Note: this checks the format only. It does not prove the branch exists. For that you need a bank or RBI data source.

Settings and config

  1. VS Code: install the Go extension; it runs gofmt on save and offers to install gopls.
  2. Rules file: “Go 1.22+, standard library first, table tests, wrap errors with fmt.Errorf("...: %w", err)”.
  3. Run go vet ./... and go test ./... in CI on every pull request.

Watch out (common AI mistakes in Go)

  • Ignored errors — x, _ := ...; ask it to handle every error.
  • Made-up packages — check on pkg.go.dev.
  • Goroutine leaks and data races — run go test -race for concurrent code.
  • Compiling a regex inside a loop — it should be a package-level variable, like above.

Try this yourself: ask AI for a Go shipping band, then prove it with table tests

Hello friends. The live chapter already walked through IFSC IsValid with a table test. This practice is a different fictional shop called Drift Pine Outfitters. You ask an AI for a Go helper Band that maps parcel weight in kilograms to Local, Regional, or National, rejects bad weights with clear errors, and proves every cutoff with go test. On this drafting machine we ran the real go 1.27.2 toolchain: the starter failed 5 subtests and passed 4, and the fixed package passed all 9 subtests.

Ravindra Bagale's Tip

Put the exact band cutoffs and the error message substrings in your prompt. Ask for table-driven tests with t.Run names you can read in the failure list. Run go test on the starter first so you see which cutoffs still fail, then ask the AI to fix only those cases.

Practice label: Drift Pine Outfitters, every weight and every band label here is fictional teaching data. It is not a real carrier or price list. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box used preexisting go 1.27.2 linux/amd64 at /usr/local/bin/go. Starter go test reported 5 failed subtests and 4 passed subtests. Fixed go test reported PASS with 9 passed subtests. No new Go toolchain was installed for this draft.

Your task: start from the buggy shipping.go that returns wrong bands and skips validation. Ask an AI to match the Local / Regional / National cutoffs, reject non-positive weights and weights above 30 kg, and keep table-driven tests in shipping_test.go.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create go.mod with module path driftpine.example/shipping and a Go version your machine supports.
  3. Save shipping.go and shipping_test.go in the same folder.
  4. Confirm the toolchain: run go version and expect a Go 1.22 or newer release.

Starter go.mod:

go.mod
module driftpine.example/shipping

go 1.22

Starter shipping.go (wrong cutoffs, skips validation):

shipping.go
// Package shipping assigns Drift Pine Outfitters shipping bands by parcel weight.
// Fictional teaching shop only — not a real carrier or price list.
// Starter: returns a label for a few ranges but skips validation and wrong bands.
package shipping

// Band returns a shipping band label for weightKg.
// Expected bands after the fix:
//   0 < kg <= 2  -> "Local"
//   2 < kg <= 10 -> "Regional"
//   10 < kg <= 30 -> "National"
// Rejects non-positive weight and weight above 30.
func Band(weightKg float64) (string, error) {
	// Starter bugs: no validation; wrong cutoffs; empty string for many inputs.
	if weightKg <= 5 {
		return "Local", nil
	}
	if weightKg <= 20 {
		return "Regional", nil
	}
	return "National", nil
}

Table tests shipping_test.go:

shipping_test.go
package shipping

import (
	"strings"
	"testing"
)

func TestBandTable(t *testing.T) {
	cases := []struct {
		name    string
		kg      float64
		want    string
		errPart string
	}{
		{"local_one_point_five", 1.5, "Local", ""},
		{"local_exact_two", 2.0, "Local", ""},
		{"regional_two_point_one", 2.1, "Regional", ""},
		{"regional_ten", 10.0, "Regional", ""},
		{"national_ten_point_one", 10.1, "National", ""},
		{"national_thirty", 30.0, "National", ""},
		{"rejects_zero", 0, "", "positive"},
		{"rejects_negative", -1, "", "positive"},
		{"rejects_over_thirty", 30.1, "", "30 kg"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got, err := Band(tc.kg)
			if tc.errPart == "" {
				if err != nil {
					t.Fatalf("Band(%v) unexpected error: %v", tc.kg, err)
				}
				if got != tc.want {
					t.Fatalf("Band(%v) = %q, want %q", tc.kg, got, tc.want)
				}
				return
			}
			if err == nil {
				t.Fatalf("Band(%v) expected error containing %q, got nil (label %q)", tc.kg, tc.errPart, got)
			}
			if !strings.Contains(err.Error(), tc.errPart) {
				t.Fatalf("Band(%v) error %q, want substring %q", tc.kg, err.Error(), tc.errPart)
			}
		})
	}
}

Suggested AI ask (copy and adapt):

go-prompt.txt
Write a Go 1.22 package shipping with func Band(weightKg float64) (string, error) for fictional Drift Pine Outfitters. Reject NaN and Inf with an error mentioning finite. Reject weightKg <= 0 with an error mentioning positive. Reject weightKg > 30 with an error mentioning 30 kg. Return Local for 0 < kg <= 2, Regional for 2 < kg <= 10, and National for 10 < kg <= 30. Add table-driven tests in shipping_test.go covering the cutoffs and the three error cases.

HOW to finish

HOW
  1. Save the starter files in one module folder.
  2. Ask your AI assistant to fix the cutoffs and add validation with the error substrings the tests search for.
  3. Run go test. On the buggy starter this drafting box saw 5 failed and 4 passed subtests.
  4. Run again after the fix. Expect PASS with 9 passed subtests.

Real go test output after the fixed package:

go-test-after.txt
PASS
ok  	driftpine.example/shipping	0.002s
Optional completed shipping.go (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if go test passes all nine subtests.

shipping.go
// Package shipping assigns Drift Pine Outfitters shipping bands by parcel weight.
// Fictional teaching shop only — not a real carrier or price list.
package shipping

import (
	"errors"
	"math"
)

// Band returns a shipping band label for weightKg.
//   0 < kg <= 2  -> "Local"
//   2 < kg <= 10 -> "Regional"
//   10 < kg <= 30 -> "National"
func Band(weightKg float64) (string, error) {
	if math.IsNaN(weightKg) || math.IsInf(weightKg, 0) {
		return "", errors.New("weight must be a finite number")
	}
	if weightKg <= 0 {
		return "", errors.New("weight must be positive")
	}
	if weightKg > 30 {
		return "", errors.New("weight must not exceed 30 kg")
	}
	if weightKg <= 2 {
		return "Local", nil
	}
	if weightKg <= 10 {
		return "Regional", nil
	}
	return "National", nil
}

Troubleshooting

HOW
  1. Problem: Band(2.1) still returns Local. Fix: Local must end at exactly 2.0 inclusive, so values above 2.0 belong to Regional.
  2. Problem: Band(0) returns a label instead of an error. Fix: reject every weight that is not greater than zero, and put the word positive in the error message.
  3. Error: go: cannot find main module. Fix: create go.mod in the same folder as shipping.go before you run go test.
  4. Problem: the over-30 case fails because the message does not match. Fix: include the substring 30 kg in that error text so the table test can find it.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name the cutoffs in the prompt

Ask for Local, Regional, and National with inclusive upper bounds at 2, 10, and 30 kilograms.
Run go test and read the t.Run names that still fail.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep error substrings stable

Tests search for positive and 30 kg inside the error text.
Ask the AI to keep those words even if it rewrites the sentence.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये cutoffs सांगा

2, 10 आणि 30 किलोग्रॅमच्या inclusive upper bounds सह Local, Regional आणि National मागा.
go test चालवा आणि अजून fail होणारी t.Run नावे वाचा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Error substrings स्थिर ठेवा

Tests error text मध्ये positive आणि 30 kg शोधतात.
AI वाक्य बदलले तरीही ती शब्द ठेवायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. Which command runs Go tests?

go test ./....

2. What is a table-driven test?

A list of input/expected cases checked in one loop.

3. Is "SBIN1001234" a valid IFSC format?

No. The 5th character must be 0.

4. Which flag finds data races?

go test -race.

Save tokens and money

SMART AI USE

Go's own tools (gofmt, go vet, go test) are free and fast. Run them first and send the AI only the real failure lines. Ask for one function plus its table test at a time.

Save these cards

INTERVIEW CARDAI Coding

How do you check AI Go code?

gofmt, go vet, then table-driven go test.
Handle every error; -race for goroutines.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Go tests vs other languages

Go: testing package built in, no install.
Java/C#: add JUnit or xUnit.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Go with AI in 3

Std lib only + examples in the prompt.
Table tests.
go vet + go test = proof.
Ravindra Bagale · ravindrabagale.com/ai-coding