Каждый Go-файл начинается с объявления пакета. Пакет группирует код — думай о нём как о папке. Имя main особенное: оно говорит компилятору, что это запускаемая программа, а не библиотека. Библиотеку назвали бы по смыслу: package utils, package db.
import
Go ничего не подключает сам: нужен пакет — импортируй его явно. fmt (от format) — стандартный пакет для вывода текста. Имя пакета пишется в двойных кавычках, несколько пакетов — в скобках:
go
import ( "fmt" "os" "time")
Компилятор строг к импортам:
Ситуация
Что пишет компилятор
Используешь fmt, но не импортировал
undefined: fmt
Импортировал, но не используешь
"os" imported and not used
func main
func — ключевое слово для объявления функции. main — точка входа: при запуске Go ищет пакет main, в нём функцию main и начинает выполнение с неё. Пустые круглые скобки — функция не принимает параметров. В фигурных скобках — тело функции.
Правила, которые ломают код новичков
Правило
Почему так
Открывающая { — на той же строке, что func, if, for
Компилятор сам ставит ; в конце строки, и перенос скобки даёт syntax error: unexpected semicolon or newline before {
Регистр важен
Пишут package main, а не Package main. Имена с заглавной буквы экспортируются из пакета: fmt.Println доступна снаружи, а функцию со строчной буквы из другого пакета вызвать нельзя
go run main.go # или go run . — запустить пакет в текущей папкеgo build # собрать исполняемый файл hello./hello
go run компилирует программу во временный файл, запускает и удаляет его — папка остаётся чистой. Идеально для экспериментов.
go build создаёт отдельный исполняемый файл. Его можно перенести на другой компьютер и запустить без установленного Go: всё встроено в бинарник. Нужен для деплоя на сервер, передачи готовой программы и финальной сборки.
Вывод через fmt
Функция
Что делает
fmt.Print
выводит аргументы без перевода строки
fmt.Println
ставит пробелы между аргументами и перевод строки в конце
fmt.Printf
форматированный вывод по шаблону с плейсхолдерами
fmt.Sprintf
то же, что Printf, но возвращает строку, а не печатает её
Println сам поставил пробелы между аргументами, поэтому лишние пробелы внутри строк не нужны. Print не добавляет ничего — перевод строки приходится писать явно через \n.
Package с заглавной буквы — ключевые слова Go пишутся строчными: package.
os импортирован, но не используется — ошибка "os" imported and not used.
{ перенесена на новую строку — syntax error: unexpected semicolon or newline before {.
Строка в одинарных кавычках — для строк нужны двойные: "Привет, GoFlix!".
Проверь себя
вопросЧем package main отличается от package utils?
main — запускаемая программа, в ней обязана быть функция main. Любое другое имя — библиотека, которую импортируют другие пакеты.
вопросЧто будет, если импортировать пакет и не использовать его?
Программа не скомпилируется: "имя" imported and not used. Go не терпит лишних импортов.
вопросЧем go run отличается от go build?
go run компилирует во временный файл, запускает и удаляет его. go build создаёт исполняемый файл, который запускается без установленного Go, — для деплоя и передачи программы.
вопросЧем отличаются Print, Println, Printf и Sprintf?
Print — без перевода строки; Println — с пробелами между аргументами и переводом строки; Printf — по шаблону с плейсхолдерами; Sprintf — как Printf, но возвращает строку.
вопросПочему в Go нельзя переносить { на новую строку?
Компилятор автоматически ставит точку с запятой в конце строки. После func main() она окажется перед {, и получится синтаксическая ошибка.
вопросКакой плейсхолдер покажет тип значения?
%T.
Ключевые выводы
📦 Программа = package main + импорты + func main() как точка входа.
Every Go file starts with a package declaration. A package groups code — think of it as a folder. The name main is special: it tells the compiler that this is an executable program, not a library. A library would be named after what it does: package utils, package db.
import
Go doesn't include anything on its own: if you need a package, import it explicitly. fmt (short for format) is the standard package for printing text. The package name goes in double quotes; several packages go in parentheses:
go
import ( "fmt" "os" "time")
The compiler is strict about imports:
Situation
What the compiler says
You use fmt but didn't import it
undefined: fmt
You imported it but don't use it
"os" imported and not used
func main
func is the keyword for declaring a function. main is the entry point: at startup Go looks for the main package, finds the main function in it, and starts execution there. The empty parentheses mean the function takes no parameters. Between the curly braces is the function body.
Rules that break beginners' code
Rule
Why it's this way
The opening { goes on the same line as func, if, for
The compiler inserts a ; at the end of the line by itself, and moving the brace down gives syntax error: unexpected semicolon or newline before {
Case matters
It's package main, not Package main. Capitalized names are exported from the package: fmt.Println is visible from outside, while a lowercase function can't be called from another package
go run main.go # or go run . — run the package in the current foldergo build # build the executable hello./hello
go run compiles the program into a temporary file, runs it, and deletes it — the folder stays clean. Perfect for experiments.
go build produces a standalone executable. You can copy it to another computer and run it without Go installed: everything is baked into the binary. What you need for deploying to a server, shipping a finished program, and final builds.
Output with fmt
Function
What it does
fmt.Print
prints the arguments without a newline
fmt.Println
adds spaces between arguments and a newline at the end
fmt.Printf
formatted output from a template with placeholders
fmt.Sprintf
same as Printf, but returns the string instead of printing it
Println added the spaces between the arguments itself, so extra spaces inside the strings aren't needed. Print adds nothing — the newline has to be written explicitly with \n.
Printf placeholders
Placeholder
What it substitutes
Example → result
%s
a string
"Dune" → Dune
%d
an integer (decimal)
2014 → 2014
%f, %.1f
a fractional number; .1 — one digit after the point
Package with a capital letter — Go keywords are written lowercase: package.
os is imported but never used — the "os" imported and not used error.
{ moved to a new line — syntax error: unexpected semicolon or newline before {.
The string is in single quotes — strings need double quotes: "Hello, GoFlix!".
Check yourself
questionHow does package main differ from package utils?
main is an executable program and must contain a main function. Any other name is a library that other packages import.
questionWhat happens if you import a package and don't use it?
The program won't compile: "name" imported and not used. Go doesn't tolerate extra imports.
questionHow is go run different from go build?
go run compiles to a temporary file, runs it, and deletes it. go build creates an executable that runs without Go installed — for deploying and shipping the program.
questionHow do Print, Println, Printf, and Sprintf differ?
Print — no newline; Println — spaces between arguments plus a newline; Printf — from a template with placeholders; Sprintf — like Printf, but returns a string.
questionWhy can't { be moved to a new line in Go?
The compiler automatically inserts a semicolon at the end of the line. After func main() it lands right before the {, and you get a syntax error.
questionWhich placeholder shows a value's type?
%T.
Key takeaways
📦 A program = package main + imports + func main() as the entry point.
🚫 The compiler is strict: an unused import or a moved { is a compile error.
▶️ go run for experiments, go build for a finished binary that doesn't need Go.
🖨️ Print, Println, Printf, Sprintf cover all output; the %s %d %f %v %T placeholders are the foundation.
🔠 Case matters: a capitalized name is exported from its package.