Skip to Content
Go 소개
book

Go 소개

by Caleb Doxsey
May 2025
Beginner to intermediate
124 pages
1h 15m
Korean
O'Reilly Media, Inc.
Content preview from Go 소개

6장. 기능

이 작품은 AI를 사용하여 번역되었습니다. 여러분의 피드백과 의견을 환영합니다: translation-feedback@oreilly.com

함수(프로시저 또는 서브루틴이라고도 함)는 0개 이상의 입력 매개변수를 0개 이상의 출력 매개변수에 매핑하는 독립적인 코드 섹션입니다. 그림 6-1에서 볼 수 있듯이 함수는 종종 블랙박스로 표현됩니다.

그림 6-1. 블랙박스 기능

이전 장에서 Go로 작성한 프로그램에서는 하나의 함수만 사용했습니다:

func main() {}

이제 두 개 이상의 함수를 사용하는 프로그램을 작성해 보겠습니다.

두 번째 기능

5장의 다음 프로그램을 다시 한 번 살펴보겠습니다:

func main() {
    xs := []float64{98,93,77,82,83}

    total := 0.0
    for _, v := range xs {
        total += v
    }
    fmt.Println(total / float64(len(xs)))
}

이 프로그램은 일련의 숫자의 평균을 계산합니다. 이와 같은 평균을 구하는 것은 매우 일반적인 문제이므로 함수로 정의하기에 이상적입니다.

average 함수는 float64조각을 가져와서 float64 하나를 반환해야 합니다. 이것을 main 함수 앞에 삽입하세요:

func average(xs []float64) float64 {
    panic("Not Implemented")
}

함수는 키워드 func 로 시작하고 그 뒤에 함수 이름을 붙입니다. 함수의 매개변수(입력)는 다음과 같이 정의됩니다: name type, name type, …. 우리 함수에는 xs 이라는 이름의 매개변수(점수 목록)가 하나 있습니다. 매개변수 뒤에는 반환 유형을 넣습니다. 매개변수와 반환 유형을 통틀어 함수의 시그니처라고 합니다.

마지막으로 중괄호 사이의 일련의 문으로 구성된 본문 함수가 있습니다. 이 본문에서는 런타임 오류를 일으키는 panic 라는 내장 함수를 호출합니다(이 장의 뒷부분에서 panic 에 대해 자세히 살펴보겠습니다). 함수 작성은 어려울 수 있으므로 전체 과정을 한 번에 구현하려고 하기보다는 관리하기 쉬운 단계로 나누는 것이 좋습니다.

이제 메인 함수의 코드를 가져와서 평균 함수로 옮겨 보겠습니다:

func average(xs []float64) float64 {
    total := 0.0
    for _, v := range xs {
      total += v
  }
  return total / float64(len(xs))
}

fmt.Println 을 return 으로 변경한 것을 알 수 있습니다. 반환 문은 함수를 즉시 중지하고 그 뒤에 있는 값을 이 함수를 호출한 함수에 반환합니다. main 을 다음과 같이 수정합니다:

func main() {
    xs := []float64{98,93,77,82,83}
    fmt.Println(average
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

효율적인 Go

효율적인 Go

Bartlomiej Plotka
핸즈온 머신러닝(3판)

핸즈온 머신러닝(3판)

오렐리앙 제롱(Aurélien Géron)
러닝 랭체인

러닝 랭체인

메이오 오신, 누노 캄포스
Go의 동시성

Go의 동시성

Katherine Cox-Buday

Publisher Resources

ISBN: 9798341659827