S SmartDocs
시리즈: Go go 80 줄 · 업데이트 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"))
}

관련 글