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 소개

5장. 배열, 슬라이스 및 맵

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

2장에서는 Go의 기본 유형에 대해 알아보았습니다. 이 장에서는 배열, 슬라이스, 맵이라는 세 가지 기본 제공 유형을 더 살펴보겠습니다.

배열

배열은 길이가 고정된 단일 유형의 요소로 이루어진 번호가 매겨진 시퀀스입니다. Go에서는 다음과 같이 보입니다:

var x [5]int

x 는 5개의 int로 구성된 배열의 예입니다. 다음 프로그램을 실행해 보세요:

package main

import "fmt"

func main() {
    var x [5]int
    x[4] = 100
    fmt.Println(x)
}

이걸 보셔야 합니다:

[0 0 0 0 100]

x[4] = 100 는 "배열 x의 다섯 번째 요소를 100으로 설정"이라고 읽어야 합니다. x[4] 이 네 번째 요소가 아닌 다섯 번째 요소를 나타내는 것이 이상하게 보일 수 있지만 문자열과 마찬가지로 배열은 0부터 인덱싱됩니다. 배열도 비슷한 방식으로 액세스합니다. fmt.Println(x) 을 fmt.Println(x[4]) 으로 변경하면 100을 얻을 수 있습니다.

다음은 배열을 사용하는 프로그램의 예시입니다:

func main() {
    var x [5]float64
    x[0] = 98
    x[1] = 93
    x[2] = 77
    x[3] = 82
    x[4] = 83

    var total float64 = 0
    for i := 0; i < 5; i++ {
        total += x[i]
    }
    fmt.Println(total / 5)
}

이 프로그램은 일련의 시험 점수의 평균을 계산합니다. 이 프로그램을 실행하면 86.6 이 표시됩니다. 프로그램을 살펴봅시다:

  1. 먼저 시험 점수를 저장하기 위해 길이 5의 배열을 만든 다음 각 요소를 성적으로 채웁니다.
  2. 다음으로 for 루프를 설정하여 총 점수를 계산합니다.
  3. 마지막으로 총 점수를 요소의 수로 나누어 평균을 구합니다.

이 프로그램은 작동하지만 Go에서 개선할 수 있는 몇 가지 기능을 제공합니다. 특히 i < 5 과 total / 5 은 우리에게 적신호를 보내야 합니다. 등급 수를 5에서 6으로 변경했다고 가정해 봅시다. 이 두 부분도 모두 변경해야 합니다. 대신 배열의 길이를 사용하는 것이 더 나을 것입니다:

var total float64 = 0
for i := 0; i < len(x); i++ {
    total += x[i]
}
fmt.Println(total / len(x))

계속해서 이러한 변경 사항을 적용하고 프로그램을 실행하세요. 오류가 표시될 것입니다:

$ go run tmp.go
# command-line arguments
.\tmp.go:19: invalid operation: total / 5 (mismatched types float64 and int)

여기서 문제는 len(x) 와 total 의 유형이 다르다는 것입니다. total 는 float64 이고 len(x) 는 int 입니다. 따라서 ...

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