Go User Manual
Basic Syntax
Variable Declaration
Go has multiple ways to declare variables. The basic declaration uses the var keyword:
// Declare variable with type
var name string = "Go"
// Type inference declaration
var age = 10
// Batch declaration
var (
firstName string
lastName string
score float64
)
// Short declaration (inside function)
message := "Hello, World!"
Go variables must be used after declaration, otherwise compilation will fail. If you need to declare an unused variable temporarily, you can use underscore _ to receive it:
result, _ := someFunction() // Ignore first return value
Constant Declaration
Constants are declared using the const keyword and can be characters, strings, booleans, or numbers:
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)
Basic Data Types
Go's basic data types include:
- Boolean: bool (true or false)
- Integers: int, int8, int16, int32, int64, and corresponding unsigned types uint, etc.
- Floating point: float32, float64
- Complex numbers: complex64, complex128
- Strings: string
Type conversion must be explicit:
var i int = 42
var f float64 = float64(i)
var s string = strconv.Itoa(i) // Integer to string
Functions
Function Definition
Go functions are defined using the func keyword:
func greet(name string) string {
return "Hello, " + name
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named return values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // No need to specify return values
}
Variadic Parameters
Functions can accept a variable number of parameters:
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Usage
result := sum(1, 2, 3, 4, 5)
Closures
Go supports closures, where functions can capture and modify variables from the outer scope:
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Usage
c := counter()
fmt.Println(c()) // 1
fmt.Println(c()) // 2
Concurrent Programming
Goroutines
Goroutines are lightweight execution units in Go with extremely low creation cost:
// Start goroutine
go func() {
fmt.Println("Hello from goroutine!")
}()
// Goroutine with parameters
go func(msg string) {
fmt.Println(msg)
}("Hello!")
Channels
Channels are the communication mechanism between goroutines:
// Create channel
ch := make(chan string)
// Send data
ch <- "message"
// Receive data
msg := <-ch
// Buffered channel
bufferedCh := make(chan int, 10)
Select
The select statement is used to wait for multiple channel operations simultaneously:
select {
case msg := <-ch1:
fmt.Println("Received:", msg)
case msg := <-ch2:
fmt.Println("Received:", msg)
case <-time.After(time.Second):
fmt.Println("Timeout")
}
Concurrency Safety
Use the sync package for concurrency control:
var (
mu sync.Mutex
count int
)
func increment() {
mu.Lock()
defer mu.Unlock()
count++
}
Error Handling
Error Returns
Go uses return values for error handling, which is the idiomatic way in Go:
result, err := doSomething()
if err != nil {
return err
}
Custom Errors
Create custom errors using the errors package:
import "errors"
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
Error Wrapping
Go 1.13 introduced error wrapping using fmt.Errorf and %w verb:
if err != nil {
return fmt.Errorf("failed to do something: %w", err)
}
Interfaces
Interface Definition
Go interfaces are implicitly implemented, requiring no explicit declaration:
type Writer interface {
Write([]byte) (int, error)
}
type Reader interface {
Read([]byte) (int, error)
}
// Common composite interface
type ReadWriter interface {
Reader
Writer
}
Empty Interface
The empty interface interface{} can store values of any type:
var i interface{} = 42
var s interface{} = "hello"
var m interface{} = map[string]int{"a": 1}
Go 1.18 introduced generics, allowing use of any instead of interface{}:
var i any = 42
Packages and Modules
Creating a Module
Use go mod init to create a new module:
go mod init github.com/username/project
Dependency Management
Add dependencies:
go get github.com/pkg/errors
Update dependencies:
go get -u all
Clean up unused dependencies:
go mod tidy
Testing
Unit Testing
Go has a built-in testing framework. Test files end with _test.go:
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
Run tests:
go test ./...
go test -v ./...
go test -cover ./...
Benchmark Tests
Benchmark functions start with Benchmark:
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
Hello()
}
}
Run benchmark tests:
go test -bench=.
Common Standard Library
fmt - Formatted I/O
fmt.Println("Hello")
fmt.Printf("Name: %s, Age: %d\n", name, age)
fmt.Sprintf("Result: %d", result)
strings - String Operations
strings.Contains(s, "sub")
strings.Split(s, ",")
strings.TrimSpace(s)
strings.ToUpper(s)
net/http - HTTP Server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, HTTP!")
})
http.ListenAndServe(":8080", nil)
json - JSON Processing
// Encode
data, _ := json.Marshal(person)
// Decode
var p Person
json.Unmarshal(data, &p)
Common Tools
gofmt - Code Formatting
gofmt -w main.go # Format and write to file
gofmt -d main.go # Show formatting differences
go vet - Static Analysis
go vet ./... # Check for code issues
go doc - Documentation Viewer
go doc fmt.Println # View function documentation
go doc fmt # View package documentation
