Menu
Coddy logo textTech

요약 - 제네릭 컬렉션

Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 107개 중 72번째.

challenge icon

챌린지

쉬움

Go의 generic에 대해 배운 모든 것을 보여 주는 generic Queue data structure를 만들어 봅시다! 스택(LIFO)과 달리 queue는 선입선출(First-In-First-Out, FIFO) 순서를 따릅니다. 즉, 먼저 추가된 첫 번째 item이 가장 먼저 제거됩니다.

코드를 두 개의 파일로 구성합니다:

  • queue.go: generic queue collection을 Define합니다.

    item을 internally 저장하는 generic struct Queue[T any]를 만드세요. queue는 다음 operations를 지원해야 합니다:

    • Enqueue(item T) - queue의 back에 item을 adds
    • Dequeue() (T, bool) - queue의 front에서 item을 제거하고 반환하며, 성공 여부를 나타내는 boolean도 함께 반환합니다( queue가 empty이면 zero value와 false를 반환).
    • Peek() (T, bool) - front item을 제거하지 않고 반환합니다(Dequeue와 동일한 반환 패턴).
    • Size() int - queue의 item 개수를 반환합니다.
    • IsEmpty() bool - queue에 item이 없으면 true를 반환합니다.

    또한 initialized된 empty queue의 pointer를 반환하는 constructor function NewQueue[T any]() *Queue[T]도 만드세요.

  • main.go: input에 따라 서로 다른 type으로 queue를 보여 줍니다.

    type indicator(int 또는 string)를 읽은 다음, queue에서 수행할 commands를 연속해서 읽습니다. 각 command는 별도의 line에 있습니다:

    • enqueue [value] - value를 queue에 추가합니다.
    • dequeue - front item을 제거하고 print합니다(queue가 empty이면 empty를 print).
    • peek - front item을 제거하지 않고 print합니다(queue가 empty이면 empty를 print).
    • size - 현재 size를 print합니다.

    done을 받을 때까지 commands를 읽습니다.

다음 input이 제공됩니다:

  • Line 1: Type indicator(int 또는 string)
  • Following lines: done까지의 Commands

예를 들어, 다음이 주어졌을 때:

int
enqueue 10
enqueue 20
enqueue 30
peek
dequeue
size
dequeue
dequeue
dequeue
done

output은 다음과 같아야 합니다:

10
10
2
20
30
empty

그리고 다음이 주어졌을 때:

string
enqueue hello
enqueue world
size
peek
dequeue
peek
done

output은 다음과 같아야 합니다:

2
hello
hello
world

queue는 integer와 string type 모두에서 동일하게 작동해야 하며, 하나의 generic implementation이 full type safety를 유지하면서 여러 concrete type을 처리하는 방식을 보여 줘야 합니다.

직접 해보기

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	
	// 타입 표시자를 읽습니다
	scanner.Scan()
	typeIndicator := scanner.Text()
	
	if typeIndicator == "int" {
		// TODO: NewQueue[int]()를 사용하여 정수 큐 생성
		// 정수 큐에 대한 명령 처리
		
		for scanner.Scan() {
			line := scanner.Text()
			if line == "done" {
				break
			}
			
			parts := strings.SplitN(line, " ", 2)
			command := parts[0]
			
			// TODO: 명령 처리: enqueue, dequeue, peek, size
			// enqueue의 경우, parts[1]에서 정수 값을 파싱
			// dequeue/peek의 경우, 큐가 비어 있으면 "empty" 출력
			_ = command
		}
	} else if typeIndicator == "string" {
		// TODO: NewQueue[string]()를 사용하여 문자열 큐 생성
		// 문자열 큐에 대한 명령 처리
		
		for scanner.Scan() {
			line := scanner.Text()
			if line == "done" {
				break
			}
			
			parts := strings.SplitN(line, " ", 2)
			command := parts[0]
			
			// TODO: 명령 처리: enqueue, dequeue, peek, size
			// enqueue의 경우, parts[1]에서 문자열 값 사용
			// dequeue/peek의 경우, 큐가 비어 있으면 "empty" 출력
			_ = command
		}
	}
	
	// 개발 중 사용되지 않는 import 오류를 피하기 위해 여기에 있습니다
	_ = strconv.Atoi
	_ = fmt.Println
}

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러