더북(TheBook)

슬라이스 삽입

슬라이스의 마지막이 아니라 첫 번째나 중간에 요소를 삽입해야 할 때가 있다. 슬라이스에 요소를 삽입하는 함수는 기본 함수로 제공되지 않으므로 직접 구현해야 한다. 다음 insert() 함수는 원본 슬라이스(s)의 특정 위치(index)에 새로운 슬라이스(new)를 삽입한다.

func insert(s, new []int, index int) []int {
return append(s[:index], append(new, s[index:]...)...)
}

먼저 새로 추가할 슬라이스(new)에 원본 슬라이스(s)의 특정 위치(index) 이후에 있는 요소를 추가한 후 원본 슬라이스(s)의 특정 위치(index) 이전에 있는 요소와 연결해준다.


package main
 
import "fmt"
 
func main() {
    s := []int{1, 2, 3, 4, 5}
 
    s = insert(s, []int{-3, -2}, 0)    // s: [-3 -2 1 2 3 4 5]
    fmt.Println(s)
 
    s = insert(s, []int{0}, 2)         // s: [-3 -2 0 1 2 3 4 5]
    fmt.Println(s)
 
    s = insert(s, []int{6, 7}, len(s)) // s: [-3 -2 0 1 2 3 4 5 6 7]
    fmt.Println(s)
}
 
func insert(s, new []int, index int) []int {
    return append(s[:index], append(new, s[index:]...)...)
}

실행 결과

[-3 -2 1 2 3 4 5]

[-3 -2 0 1 2 3 4 5]

[-3 -2 0 1 2 3 4 5 6 7]

다음 insert2() 함수에는 방금 사용한 insert() 함수 같은 기능을 append() 함수를 사용하지 않고 구현한다. make() 함수를 사용해 원본 슬라이스의 길이와 삽입할 슬라이스의 길이를 합한 길이로 슬라이스를 생성한 후, copy() 함수로 각 위치에 요소들을 직접 복사해준다.

func insert2(s, new []int, index int) []int {
    result := make([]int, len(s)+len(new))
    position := copy(result, s[:index])
    position += copy(result[position:], new)
    copy(result[position:], s[index:])
    return result
}

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.