G
Funções
Go Syntax Guide
Definir e chamar funções em Go
Funções
Definir e chamar funções em Go
Go funções (go)
package main
import "fmt"
// Function with parameters and return value
func add(a, b int) int {
return a + b
}
// Function with multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// Variadic function
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
// Anonymous function
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Struct definition
type Person struct {
Name string
Age int
}
// Method (function attached to a type)
func (p Person) Greet() string {
return fmt.Sprintf("Hello, I'm %s", p.Name)
}
// Pointer receiver method (can modify the struct)
func (p *Person) Birthday() {
p.Age++
}
// Interface definition
type Speaker interface {
Speak() string
}
// Implement interface
func (p Person) Speak() string {
return fmt.Sprintf("My name is %s and I'm %d years old", p.Name, p.Age)
}
// Function that accepts interface
func introduce(s Speaker) {
fmt.Println(s.Speak())
}
// Generic function (Go 1.18+)
func printSlice[T any](slice []T) {
for _, item := range slice {
fmt.Printf("%v ", item)
}
fmt.Println()
}
// Main function demonstrating usage
func main() {
// Basic function calls
result := add(5, 3)
fmt.Printf("5 + 3 = %d\n", result)
// Multiple return values
quotient, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("10 / 2 = %.2f\n", quotient)
}
// Variadic function
total := sum(1, 2, 3, 4, 5)
fmt.Printf("Sum: %d\n", total)
// Closure
increment := counter()
fmt.Println(increment()) // 1
fmt.Println(increment()) // 2
// Methods
person := Person{Name: "John", Age: 25}
fmt.Println(person.Greet())
person.Birthday()
fmt.Printf("After birthday: %d years old\n", person.Age)
// Interface
introduce(person)
// Generics
numbers := []int{1, 2, 3, 4, 5}
names := []string{"Alice", "Bob", "Charlie"}
printSlice(numbers)
printSlice(names)
}
Explanation
As funções em Go são declaradas com a palavra-chave func e podem retornar múltiplos valores, o que é um padrão comum para tratamento de erros.
Common Use Cases
- Reutilização de código
- Modularidade
- Implementar blocos lógicos específicos
Related Go Syntax
Master Funções in Go
Understanding Funções is fundamental to writing clean and efficient Go code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Funções effectively in your Go projects.
Key Takeaways
- Reutilização de código
- Modularidade
- Implementar blocos lógicos específicos