Serie: Go
go
80 líneas
· Actualizado 2026-04-18
main.go
Go/part1-language/examples/06_funcs/main.go
// Demonstrates functions, multiple returns, variadic, closures, methods.
package main
import (
"errors"
"fmt"
)
type Rectangle struct {
W, H float64
}
func NewRectangle(w, h float64) *Rectangle { return &Rectangle{W: w, H: h} }
func (r Rectangle) Area() float64 { return r.W * r.H }
func (r *Rectangle) Scale(f float64) {
r.W *= f
r.H *= f
}
var ErrDivByZero = errors.New("divide by zero")
func divide(a, b int) (int, error) {
if b == 0 {
return 0, ErrDivByZero
}
return a / b, nil
}
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func counter() func() int {
n := 0
return func() int {
n++
return n
}
}
func wrapped(name string) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("wrapped(%s): %w", name, err)
}
}()
_, err = divide(1, 0)
return err
}
func main() {
if q, err := divide(10, 3); err == nil {
fmt.Println("10/3 =", q)
}
if _, err := divide(5, 0); err != nil {
fmt.Println("err:", err, "is ErrDivByZero?", errors.Is(err, ErrDivByZero))
}
fmt.Println("sum:", sum(1, 2, 3, 4))
fmt.Println("sum spread:", sum([]int{10, 20, 30}...))
c := counter()
c()
c()
fmt.Println("counter:", c())
r := NewRectangle(3, 4)
fmt.Println("area before:", r.Area())
r.Scale(2)
fmt.Println("area after :", r.Area())
fmt.Println(wrapped("demo"))
}
Artículos relacionados
Go
go
Actualizado 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
Leer artículo →
Go
go
Actualizado 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
Leer artículo →
Go
go
Actualizado 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
Leer artículo →
Go
go
Actualizado 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
Leer artículo →
Go
go
Actualizado 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
Leer artículo →
Go
go
Actualizado 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
Leer artículo →