Go 기초

Go Functions and Multiple Return Values

Functions in Go can return several values. Learn the result-and-error pattern and variadic parameters.

  • 초급
  • 4분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Parameters and results
  • Returning a value and an error
  • Variadic functions
divide(a, b)
divide(10, 4)2.5, nil
divide(1, 0)0, "cannot divide by zero"

A result and an error

A function groups code under a name. Go functions can return several values, and the usual pattern is to return a result together with an error.

divide returns the result and an error; nil means there was no error. The underscore ignores a value you do not need. numbers ...int accepts any number of integers, and the named result total is returned by the bare return.

핵심 포인트

  1. A function can return more than one value.
  2. nil means there was no error.
  3. _ ignores a value you do not need.

실행 가능한 Go 예제

Go
코드 실행 →
main.go
package main

import (
	"errors"
	"fmt"
)

func area(width, height int) int {
	return width * height
}

func divide(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return a / b, nil
}

func sum(numbers ...int) (total int) {
	for _, n := range numbers {
		total += n
	}
	return
}

func main() {
	fmt.Println(area(4, 5))

	if result, err := divide(10, 4); err == nil {
		fmt.Println(result)
	}
	_, err := divide(1, 0)
	fmt.Println(err)

	fmt.Println(sum(1, 2, 3, 4))
}
이 예제의 실행 버튼 만들기 코드 실행 결과
20
2.5
cannot divide by zero
10

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Fibonacci Sequence →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지