할 일 삭제하기
Coddy GO 여정의 로직 & 흐름 섹션에 포함된 레슨 — 68개 중 24번째.
챌린지
쉬움작업 관리 시스템의 이번 파트에서는 목록에서 작업을 제거하는 기능을 구현하게 됩니다. 이 챌린지는 append 함수를 사용하여 특정 요소가 없는 슬라이스를 재구성하는 슬라이스 조작에 초점을 맞추며, 데이터 구조에서 항목을 영구적으로 제거하는 방법을 보여줍니다.
세 가지 입력을 받게 됩니다:
- 작업 수를 나타내는 문자열 (예:
"4") - 다음 형식의 작업 데이터를 포함하는 문자열:
"name1:status1,name2:status2,name3:status3"(여기서 status는"true"또는"false"입니다. 예:"Buy groceries:false,Call dentist:true,Finish project:false,Review code:true") - 제거할 작업의 인덱스를 나타내는 문자열 (예: 두 번째 작업의 경우 0 기반 인덱스를 사용하여
"1")
여러분의 과제는 다음과 같습니다:
- 이전 챌린지와 동일하게
Name(string) 및Completed(bool) 필드를 가진Task구조체를 정의합니다. Task구조체 슬라이스와 인덱스(int)를 매개변수로 받는removeTask라는 함수를 만듭니다.removeTask함수 내부에서,append를 사용하여 대상 인덱스 이전과 이후의 요소를 결합함으로써 해당 인덱스의 작업이 제거된 새 슬라이스를 반환합니다.- 두 번째 입력에서 작업 데이터를 파싱하여 작업 슬라이스를 생성합니다:
- 입력을 쉼표로 분리하여 개별 작업 항목을 얻습니다.
- 각 항목을 콜론으로 분리하여 이름과 상태를 구분합니다.
- 상태 문자열을 불리언으로 변환합니다 (
"true"는true로,"false"는false로).
- 세 번째 입력 문자열을 정수로 변환하여 작업 인덱스를 얻습니다.
removeTask함수를 호출하기 전에 제거될 작업의 이름을 저장합니다.- 슬라이스와 인덱스를 사용하여
removeTask함수를 호출하고 반환된 슬라이스를 저장합니다. - 작업을 제거한 후, 이전 챌린지와 동일한 형식을 사용하여 남은 모든 작업을 표시합니다:
- 완료된 작업의 경우:
"[x] [task_name]" - 미완료 작업의 경우:
"[ ] [task_name]"
- 완료된 작업의 경우:
- 확인 메시지를 출력합니다:
"Task '[task_name]' removed successfully!" - 업데이트된 요약을 출력합니다:
"Total: [total_count] tasks ([completed_count] completed, [incomplete_count] remaining)"
인덱스 문자열을 정수로 변환하려면 strconv 패키지를 사용하세요. 이 챌린지는 append를 사용하여 대상 요소 전후의 부분을 결합하여 슬라이스를 재구성함으로써, 나머지 요소의 순서를 유지하면서 컬렉션에서 항목을 효과적으로 제거하는 방법을 보여줍니다.
직접 해보기
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Task struct {
Name string
Completed bool
}
func completeTask(tasks *[]Task, index int) {
(*tasks)[index].Completed = true
}
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
_ = scanner.Text() // Read but don't use the number of tasks
scanner.Scan()
taskDataStr := scanner.Text()
scanner.Scan()
indexStr := scanner.Text()
// Parse task data
taskEntries := strings.Split(taskDataStr, ",")
tasks := make([]Task, len(taskEntries))
for i, entry := range taskEntries {
parts := strings.Split(entry, ":")
if len(parts) >= 2 {
name := parts[0]
status := parts[1] == "true"
tasks[i] = Task{Name: name, Completed: status}
}
}
// Convert index string to integer
index, _ := strconv.Atoi(indexStr)
// Complete the task
taskName := tasks[index].Name
completeTask(&tasks, index)
// Display all tasks
for _, task := range tasks {
if task.Completed {
fmt.Printf("[x] %s\n", task.Name)
} else {
fmt.Printf("[ ] %s\n", task.Name)
}
}
// Print confirmation message
fmt.Printf("Task '%s' marked as completed!\n", taskName)
// Count completed and incomplete tasks
completedCount := 0
for _, task := range tasks {
if task.Completed {
completedCount++
}
}
incompleteCount := len(tasks) - completedCount
// Print summary
fmt.Printf("Total: %d tasks (%d completed, %d remaining)\n", len(tasks), completedCount, incompleteCount)
}