Menu
Coddy logo textTech

슬라이스 복사하기

Coddy GO 여정의 기초 섹션에 포함된 레슨 — 109개 중 82번째.

Go의 copy 함수는 한 슬라이스에서 다른 슬라이스로 요소를 복사할 수 있게 해줍니다.

소스 슬라이스와 대상 슬라이스를 생성합니다:

source := []int{1, 2, 3}
dest := make([]int, 2)  // 길이가 2인 대상

// 소스에서 대상으로 복사
copied := copy(dest, source)

fmt.Println("Source:", source)
fmt.Println("Destination:", dest)
fmt.Println("Number of elements copied:", copied)

결과:

Source: [1 2 3]
Destination: [1 2]
Number of elements copied: 2

copy 함수는 대상 슬라이스에 들어갈 수 있는 만큼의 요소만 복사합니다.

challenge icon

챌린지

초급

이 챌린지에서는 copy 함수를 사용하여 한 슬라이스에서 다른 슬라이스로 요소를 복사하는 연습을 합니다.

과일 이름이 포함된 source와 3개의 요소를 수용할 수 있는 빈 슬라이스인 destination, 두 개의 슬라이스가 있습니다. 여러분의 과제는 copy 함수를 사용하여 source에서 destination으로 요소를 복사하는 것입니다.

복사한 후, destination 슬라이스의 내용을 출력하세요.

치트 시트

copy 함수는 한 슬라이스에서 다른 슬라이스로 요소를 복사합니다:

source := []int{1, 2, 3}
dest := make([]int, 2)  // Destination with length 2

// Copy from source to destination
copied := copy(dest, source)

fmt.Println("Source:", source)
fmt.Println("Destination:", dest)
fmt.Println("Number of elements copied:", copied)

copy 함수는 대상(destination) 슬라이스에 들어갈 수 있는 만큼의 요소만 복사하며, 복사된 요소의 개수를 반환합니다.

직접 해보기

package main

import "fmt"

func main() {
	// 과일 이름이 포함된 소스 슬라이스
	source := []string{"apple", "banana", "cherry", "date"}
	
	// 3개의 요소를 수용할 수 있는 목적지 슬라이스 생성
	destination := make([]string, 3)
	
	// TODO: copy 함수를 사용하여 소스에서 목적지로 요소를 복사하세요
	
	
	// 목적지 슬라이스 출력
	fmt.Println("Destination slice:", destination)
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

기초의 모든 레슨