Explain it simply
Go syntax, simply
Go's syntax is deliberately small and easy to read. Reading any file from top to bottom, you always meet the package name first, then the imported packages, then the functions.
You do not type a semicolon after each statement; the compiler adds them at line ends for you. Because of that rule, where you break a line suddenly matters. And names that start with a capital letter are the ones a package shows to the outside world.
Problem → Why → Solution
The problem: moving the brace to the next line breaks the build
Developers coming from C# or C++ often put a function's `{` on its own line. Do the same in Go and the code looks fine, yet the compiler rejects it with 'unexpected semicolon or newline'. Getting a semicolon error in code that contains no semicolons at all is confusing at first.
package main
import "fmt"
func main()
{
fmt.Println("Hi")
}
// ./main.go:6:1: syntax error: unexpected semicolon or newline before {Why this happens
Go's lexer, the part that splits code into tokens, adds a semicolon at the end of a line when the line's last token is an identifier, a literal, `)`, `]`, `}` or one of a few keywords such as `return` and `break`. `func main()` ends with `)`, so it becomes `func main();`, and the `{` on the next line is no longer the function body but a stray block. Keep `{` on the same line as `)` and the problem disappears.
Core concept: how to read a Go file
Every Go file contains three parts in this order. First the `package` clause; all files in one folder must share the same package name. Second the `import` declarations, grouped in parentheses when there is more than one. Third the top-level declarations, `func`, `var`, `const` and `type`, which may appear in any order. A function does not have to be declared above the place that calls it.
Inside a function body, statements run from top to bottom. Blocks are always wrapped in `{ }`, and `if` and `for` require braces even around a single statement. In exchange, conditions need no C-style parentheses: you write `if count > 0 {`.
Names are case-sensitive, and the first letter carries meaning. A name starting with a capital letter, such as `Println`, is exported and other packages can use it; a name starting with a lowercase letter, such as `helper`, is visible only inside its own package. Go has no `public` or `private` keywords; this single rule does the job.
Where the lexer inserts semicolons
----------------------------------
func main() { line ends with "{" -> no semicolon added
msg := "hi" line ends with a literal -> ";" added
fmt.Println(msg) line ends with ")" -> ";" added
} line ends with "}" -> ";" added
func main() line ends with ")" -> ";" added (!)
{ "{" now starts a stray block -> syntax errorComments use `//` for one line and `/* */` for several. A comment placed directly above a declaration is a doc comment, which `go doc` displays. Finally, nobody needs to argue about indentation, spacing or import order: `gofmt` indents with tabs and rewrites everything into one standard layout. (The code on this site is shown with four spaces for readability.)
The semicolon rule also decides how you split a long line. To break an expression, end the line with the operator: `total := a +` and then `b` on the next line. If you end the line at `total := a` and start the next one with `+ b`, a semicolon lands after `a` and you get the compile error `+b (value of type int) is not used`. When you spread function arguments over several lines, the last argument also needs a trailing comma, or the compiler reports `unexpected newline in argument list; possibly missing comma or )`.
- package: which package
- import: which packages it uses
- func, var, const, type declarations
- main() runs top to bottom
Picture an invisible semicolon at the end of each line and you will never misplace a brace again.
General pattern: the layout of a Go file
// Package name does one thing well.
package name
import (
"first/package"
"second/package"
)
func ExportedName() { /* usable from other packages */ }
func unexportedName() { /* only inside this package */ }The package comment and clause come first, then the import group, then declarations. The first letter of a function name decides whether other packages can see it. The opening brace `{` always sits on the same line as its declaration.
Example: a greeting card program
This program has a doc comment, a grouped import, variables declared with `:=`, an end-of-line comment, and both `Println` and `Printf`. Before running it, work out what `len(title)` will be.
// Command greet prints a short greeting card.
package main
import (
"fmt"
"strings"
)
func main() {
name := "Go learner" // short variable declaration
title := strings.ToUpper("syntax")
fmt.Println("Hello,", name)
fmt.Println("Today's topic:", title)
fmt.Printf("%s has %d letters\n", title, len(title))
}Code breakdown
- Doc comment
// Command greet prints a short greeting card.Placed directly above `package`, this is the program's doc comment. For a command, Go convention starts it with 'Command' and the command's name.
- Grouped imports
import (Both packages are grouped in parentheses, one per line. `gofmt` sorts the names in this group alphabetically.
- Calling an exported function
title := strings.ToUpper("syntax")`ToUpper` starts with a capital T, so it can be called from outside the `strings` package. The result `"SYNTAX"` goes into `title`, which the compiler knows is a string.
- Statements without semicolons
fmt.Println("Hello,", name)The line ends with `)`, so the lexer inserts the semicolon. `Println` puts a space between its arguments, printing `Hello, Go learner`.
- Formatting verbs
fmt.Printf("%s has %d letters\n", title, len(title))`%s` takes a string and `%d` an integer. `len(title)` is the string's length in bytes, and six ASCII letters give 6.
Hello, Go learner
Today's topic: SYNTAX
SYNTAX has 6 lettersDouble quotes, backticks and single quotes
The three kinds of quotes mean three different things in Go. Double quotes `"..."` make an interpreted string where escapes such as `\n` and `\t` work. Backticks make a raw string: no escapes, and it keeps several lines exactly as written, which is handy for JSON and regular expressions. Single quotes such as `'G'` are not a string at all but one character's Unicode code point, a rune.
package main
import "fmt"
func main() {
json := `{"name": "Go", "fast": true}`
poem := `first line
second line`
letter := 'G'
fmt.Println("tab:\there")
fmt.Println(json)
fmt.Println(poem)
fmt.Println(letter, string(letter))
}The last line prints `71 G`: printing a rune directly shows its number (71 is G's code point), and `string(letter)` turns it back into text.
In real projects
Syntax rules in real projects
Go teams barely argue about code style, because the `gofmt` layout is the one standard. Editors format on every save, and many CI pipelines run `gofmt -l .` to list unformatted files and fail the build if there are any. That is why every open-source Go project you open looks familiar.
The exported-name rule is also the basis of package design. A library's capitalized functions are its promised public API, while lowercase helpers can change freely without breaking users. Write a doc comment above every exported name and documentation sites such as pkg.go.dev display it automatically. Renaming `Parse` to `parse` is therefore a breaking change for every project that imports the package, which is why teams think carefully before exporting a name.
Common mistakes
Common syntax mistakes
1. Putting `{` on its own line
Breaking the line after `func main()` or `if x > 0` and writing `{` below lets a semicolon slip in, giving `unexpected semicolon or newline before {`. Always end the line with `{`.
2. Calling a package function in lowercase
`fmt.println("Hi")` fails with `undefined: fmt.println`, because unexported names are invisible outside their package. Every function you call from the standard library starts with a capital letter: `fmt.Println`.
3. Writing a string in single quotes
`name := 'Hello'` gives `more than one character in rune literal`. Single quotes hold exactly one character, a rune; use `"Hello"` for text.
4. Declaring a variable and never using it
Declaring `name := "Go"` inside a function and never using it is the compile error `declared and not used: name`. While experimenting, print it with `fmt.Println(name)`; if you no longer need it, delete the line.
Best practices
Best practices
- Set your editor to run `gofmt` on save so you never align code by hand.
- Capitalize a name only when code outside the package really needs it; when unsure, keep it unexported.
- When you split a long line, end it with an operator or a comma.
Mini challenge
Mini challenge: a name badge
Print a badge that shows a name in capitals framed by lines of stars. The frame's width must depend on the name's length.
- Use a grouped import of `fmt` and `strings`
- Write a one-line doc comment above `main`
- The frame line is `len(name)+4` stars long (use `strings.Repeat`)
- Print the middle line as `* NAME *` with `Printf`
package main
// TODO: grouped import
// TODO: doc comment for main
func main() {
name := "Mya Mya"
// TODO: border := a line of stars, len(name)+4 long
// TODO: print border, "* NAME *" with Printf, border
}Expected: *********** * MYA MYA * ***********
Show hint
`"* "` and `" *"` add four characters to the middle line, which is why the frame is `len(name)+4` long. The format string is `"* %s *\n"`.
Show solution
package main
import (
"fmt"
"strings"
)
// main prints a name badge framed by lines of stars.
func main() {
name := "Mya Mya"
border := strings.Repeat("*", len(name)+4)
fmt.Println(border)
fmt.Printf("* %s *\n", strings.ToUpper(name))
fmt.Println(border)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Every Go file is ordered: package clause, imports, then top-level declarations.
- The lexer inserts semicolons at line ends, so `{` always stays on the same line.
- Capitalized names are exported; lowercase names are visible only inside their package.
- "..." is a string, backticks make a raw string, '...' is a single rune, and gofmt keeps the layout uniform.
Go release history — Go