Go Tutorial
A simple, fast language built for servers and concurrency.
Getting started3 lessons
Basics25 lessons
- 4Variables and Typesvar, := and basic types.
- 5If, For and SwitchGo has one loop: for.
- 6Declare Variablesvar and := in detail.
- 7Variable Naming RulesValid names and exported names.
- 8ConstantsValues that never change.
- 9Go OutputPrint, Println and Printf.
- 10Declare Multiple VariablesDeclare several variables in one line with commas or a var block.
- 11Zero Values and newVariables without a value get a zero value: 0, an empty string, false or nil.
- 12VariablesDeclare with var or the short form :=.
- 13Constants and iotaconst holds fixed values.
- 14Basic Typesint, int64, uint8, float64, string, bool, byte and rune.
- 15Type ConversionGo never converts types implicitly.
- 16Printf FormattingVerbs: %v any value, %d int, %s string, %f float, %q quoted, %T type, %5.2f width and prec.
- 17Println, Sprintf and ErrorfPrintln adds spaces and newline, Sprintf returns a string and Errorf builds errors.
- 18Reading Inputfmt.Scan and bufio.Scanner read input.
- 19Arithmetic and Operators+ - * / % and bit operators.
- 20The math Packagemath has Sqrt, Pow, Abs, Floor, Ceil, Max, Min, Pi and more.
- 21The strings Packagestrings has Contains, Split, Join, Replace, ToUpper, TrimSpace, HasPrefix and more.
- 22Strings, Bytes and RunesStrings are UTF-8 bytes.
- 23Booleans and Logicbool holds true or false.
- 24Scope and ShadowingVariables live in their block.
- 25Comparing ValuesArrays and structs are comparable with ==.
- 26min, max and clearGo 1.21 added the builtins min, max and clear.
- 27The slices Packageslices has Sort, Contains, Index, Reverse, Max and more for any slice.
- 28The maps Packagemaps.Keys and maps.Values return iterators and maps.Clone copies a map.
Data types6 lessons
- 29Data TypesThe basic types.
- 30StringsText and the strings package.
- 31Numbers and strconvParsing and converting.
- 32Booleans, Integers and FloatsInteger sizes are int8 to int64 and uint8 to uint64, plus int and uint.
- 33Runes, Bytes and UnicodeA string is a read only sequence of bytes.
- 34Custom Typestype Celsius float64 creates a new type with its own methods.
Operators3 lessons
Control flow12 lessons
- 38If, Else If and Nested IfConditions in detail.
- 39SwitchSingle and multi case.
- 40For LoopsCounting, conditions and range.
- 41Labels, break and continueA label names a loop so break and continue can target an outer loop from inside a nested o.
- 42Type Switch and fallthroughA type switch checks the dynamic type held by an interface.
- 43if and elseNo parentheses, braces required.
- 44for Is the Only Loopfor has three parts, a while form and an infinite form.
- 45rangerange gives index and value for slices, keys and values for maps and runes for strings.
- 46switchswitch does not fall through by default.
- 47break, continue and Labelsbreak leaves, continue skips and labels target outer loops.
- 48deferdefer runs a call when the function returns, in last in first out order.
- 49Simple Programs: Sum and FactorialCombine loops and functions to solve small problems.
Data23 lessons
- 50Arrays, Slices and MapsCollections.
- 51Structs and MethodsCustom types.
- 52ArraysFixed size lists.
- 53SlicesFlexible views.
- 54MapsKey value data.
- 55Slices In DepthRemove and insert with append and re-slicing.
- 56Maps In DepthWriting to a nil map panics, so create it with make.
- 57Sortingsort.Ints and sort.Strings sort basic slices.
- 58strings.Builder and Helpersstrings.Builder builds text efficiently.
- 59ArraysAn array has a fixed length that is part of its type.
- 60SlicesSlices are flexible views of arrays.
- 61make and Capacitymake creates slices and maps with a length and capacity.
- 62copy and SharingSlices share memory.
- 63Slices of SlicesA slice of slices builds a grid.
- 64MapsMaps store key value pairs.
- 65Iterating Maps in OrderMap order is random.
- 66StructsA struct groups fields.
- 67Pointers& takes an address and * reads through a pointer.
- 68MethodsA method is a function with a receiver.
- 69Struct EmbeddingEmbed a struct to reuse its fields and methods.
- 70InterfacesAn interface lists methods.
- 71Type Assertions and SwitchesCheck the dynamic type of an interface value with .(T) or a type switch.
- 72GenericsType parameters let one function work for many types.
Functions and errors27 lessons
- 73FunctionsMultiple returns.
- 74ErrorsReturn and check errors.
- 75InterfacesBehaviour by shape.
- 76Parameters, Returns and RecursionMore on functions.
- 77Defer, Panic and RecoverClean up and last resorts.
- 78Closures and Function ValuesFunctions are values.
- 79Variadic Functions and Method ValuesA variadic parameter collects extra arguments into a slice.
- 80Packages, init and ImportsEvery file belongs to a package.
- 81Errors In PracticeReturn errors, add context with fmt.Errorf and %w, and handle them once at the right level.
- 82Functionsfunc name(params) result.
- 83Named ReturnsName the results to document them.
- 84Variadic FunctionsUse ...T to accept any number of arguments as a slice.
- 85Function Values and ClosuresFunctions are values.
- 86ErrorsFunctions return an error as the last value.
- 87Custom Errors and Wrappingerrors.New makes an error and %w wraps one.
- 88panic and recoverpanic stops normal flow.
- 89Packages, main and initEvery program starts in package main.
- 90Testing BasicsTests live in _test.go files and use the testing package.
- 91The time Packagetime has Duration, Now, Since and formatting with a reference layout.
- 92JSONencoding/json Marshal and Unmarshal convert structs and JSON.
- 93Files with osos.WriteFile and os.ReadFile handle small files quickly.
- 94bufio Scannerbufio.Scanner reads line by line from any reader.
- 95The sort Packagesort.Ints, sort.Strings and sort.Slice order data.
- 96strings.BuilderBuilder joins many pieces efficiently.
- 97Practice: Word CountCount words with a map.
- 98Practice: FibonacciGenerate numbers with a loop and multiple assignment.
- 99Practice: Reverse and PalindromeReverse runes to support Unicode.
ConcurrencyPremium2 lessons
Advanced GoPremium11 lessons
- 102PointersAddresses and shared values.
- 103Struct Tags, Embedding and CompositionReuse without inheritance.
- 104GenericsType parameters (Go 1.18+).
- 105Custom Errors and Wrappingerrors.Is and errors.As.
- 106WaitGroups and MutexesCoordinating goroutines.
- 107Select, Timeouts and Worker PoolsPatterns for real programs.
- 108Context and Cancellationcontext carries deadlines, cancellation signals and request values across goroutines and A.
- 109JSON with encoding/jsonMarshal turns values into JSON and Unmarshal reads it back.
- 110Files and ioos.ReadFile and os.WriteFile handle whole files.
- 111Embedding Interfaces and Method SetsInterfaces can embed other interfaces.
- 112sync/atomic, Once and sync.Poolatomic counters avoid locks for simple values.
Go in practicePremium8 lessons
- 113Testing with go testTable driven tests.
- 114Building an HTTP Servernet/http basics.
- 115Benchmarks and ProfilingBenchmark functions start with Benchmark and loop b.N times.
- 116Modules and Toolinggo mod tidy cleans dependencies, go get adds one, go vet finds suspicious code, gofmt form.
- 117Databases with database/sqldatabase/sql provides a generic interface to databases.
- 118REST APIs with net/http and FrameworksSince Go 1.22 the standard mux supports methods and path parameters.
- 119Docker and DeploymentGo builds one static binary, so a tiny Docker image works.
- 120Go Best PracticesAccept interfaces and return structs, handle every error, keep packages small, prefer comp.