Manuale Utente di Go
Sintassi di Base
Dichiarazione delle Variabili
Go offre molteplici modi per dichiarare le variabili. La dichiarazione di base usa la parola chiave var:
// 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!"
Le variabili Go devono essere usate dopo la dichiarazione, altrimenti la compilazione fallirà. Se devi dichiarare temporaneamente una variabile non utilizzata, puoi usare il carattere di underscore _ per riceverla:
result, _ := someFunction() // Ignore first return value
Dichiarazione delle Costanti
Le costanti si dichiarano con la parola chiave const e possono essere caratteri, stringhe, valori booleani o numeri:
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)
Tipi di Dati di Base
I tipi di dati di base di Go includono:
- Booleano: bool (true o false)
- Interi: int, int8, int16, int32, int64 e i corrispondenti tipi senza segno uint, ecc.
- Virgola mobile: float32, float64
- Numeri complessi: complex64, complex128
- Stringhe: string
La conversione di tipo deve essere esplicita:
var i int = 42
var f float64 = float64(i)
var s string = strconv.Itoa(i) // Integer to string
Funzioni
Definizione di Funzione
Le funzioni Go si definiscono con la parola chiave func:
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
}
Parametri Variadici
Le funzioni possono accettare un numero variabile di parametri:
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Usage
result := sum(1, 2, 3, 4, 5)
Closure
Go supporta le closure, cioè funzioni che possono catturare e modificare variabili dell'ambiente esterno:
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Usage
c := counter()
fmt.Println(c()) // 1
fmt.Println(c()) // 2
Programmazione Concorrente
Goroutine
Le goroutine sono unità di esecuzione leggere con un costo di creazione estremamente basso:
// Start goroutine
go func() {
fmt.Println("Hello from goroutine!")
}()
// Goroutine with parameters
go func(msg string) {
fmt.Println(msg)
}("Hello!")
Channel
I channel sono il meccanismo di comunicazione tra le goroutine:
// Create channel
ch := make(chan string)
// Send data
ch <- "message"
// Receive data
msg := <-ch
// Buffered channel
bufferedCh := make(chan int, 10)
Select
L'istruzione select viene usata per attendere contemporaneamente più operazioni su channel:
select {
case msg := <-ch1:
fmt.Println("Received:", msg)
case msg := <-ch2:
fmt.Println("Received:", msg)
case <-time.After(time.Second):
fmt.Println("Timeout")
}
Sicurezza della Concorrenza
Usa il pacchetto sync per il controllo della concorrenza:
var (
mu sync.Mutex
count int
)
func increment() {
mu.Lock()
defer mu.Unlock()
count++
}
Gestione degli Errori
Restituzione degli Errori
Go usa i valori di ritorno per la gestione degli errori, che è il modo idiomatico in Go:
result, err := doSomething()
if err != nil {
return err
}
Errori Personalizzati
Crea errori personalizzati usando il pacchetto errors:
import "errors"
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
Wrapping degli Errori
Go 1.13 ha introdotto il wrapping degli errori usando fmt.Errorf e il verbo %w:
if err != nil {
return fmt.Errorf("failed to do something: %w", err)
}
Interfacce
Definizione di Interfaccia
Le interfacce Go sono implementate implicitamente e non richiedono dichiarazioni esplicite:
type Writer interface {
Write([]byte) (int, error)
}
type Reader interface {
Read([]byte) (int, error)
}
// Common composite interface
type ReadWriter interface {
Reader
Writer
}
Interfaccia Vuota
L'interfaccia vuota interface{} può contenere valori di qualsiasi tipo:
var i interface{} = 42
var s interface{} = "hello"
var m interface{} = map[string]int{"a": 1}
Go 1.18 ha introdotto i generics, che permettono di usare any al posto di interface{}:
var i any = 42
Pacchetti e Moduli
Creare un Modulo
Usa go mod init per creare un nuovo modulo:
go mod init github.com/username/project
Gestione delle Dipendenze
Aggiungi dipendenze:
go get github.com/pkg/errors
Aggiorna le dipendenze:
go get -u all
Pulisci le dipendenze non utilizzate:
go mod tidy
Test
Test Unitari
Go ha un framework di test integrato. I file di test terminano con _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)
}
}
Esegui i test:
go test ./...
go test -v ./...
go test -cover ./...
Test di Benchmark
Le funzioni di benchmark iniziano con Benchmark:
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
Hello()
}
}
Esegui i test di benchmark:
go test -bench=.
Libreria Standard Comune
fmt - I/O Formattato
fmt.Println("Hello")
fmt.Printf("Name: %s, Age: %d\n", name, age)
fmt.Sprintf("Result: %d", result)
strings - Operazioni sulle Stringhe
strings.Contains(s, "sub")
strings.Split(s, ",")
strings.TrimSpace(s)
strings.ToUpper(s)
net/http - Server HTTP
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, HTTP!")
})
http.ListenAndServe(":8080", nil)
json - Elaborazione JSON
// Encode
data, _ := json.Marshal(person)
// Decode
var p Person
json.Unmarshal(data, &p)
Strumenti Comuni
gofmt - Formattazione del Codice
gofmt -w main.go # Format and write to file
gofmt -d main.go # Show formatting differences
go vet - Analisi Statica
go vet ./... # Check for code issues
go doc - Visualizzatore della Documentazione
go doc fmt.Println # View function documentation
go doc fmt # View package documentation
