Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 56 of 60 · Go

Generating Go Code – `go generate` & Templates

Duration: 20 minutes

Code Generation

This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.

go generate runs commands specified in source files.

//go:generate stringer -type=Day
type Day int

const (
    Sunday Day = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)

Run with:

$ go generate ./...

Using text/template to emit code

import "text/template"

const tmpl = `package {{.Pkg}}

// {{.Name}} holds {{.Desc}}
type {{.Name}} struct { {{range .Fields}}{{.Name}} {{.Type}} ` + "`json:\"{{.JSON}}\"`" + `{{end}} }
`

type field struct { Name, Type, JSON string }

data := struct{ Pkg, Name, Desc string; Fields []field }{ "model", "User", "user data", []field{{"ID","int","id"},{"Name","string","name"}} }

t, _ := template.New("code").Parse(tmpl)
 t.Execute(os.Stdout, data)

Info

go:embed works hand‑in‑hand with go generate for embedding generated assets.

Previous: Reading & Writing CSV FilesNext: Testing HTTP Handlers – Table‑Driven Approach