删除任务
本课属于 Coddy GO 学习旅程的“逻辑与流程”单元。第 24 课,共 68 课。
挑战
简单在任务管理系统的这一部分中,你将实现从列表中删除任务的功能。本次挑战将重点介绍如何使用 append 函数操作切片,通过重建切片来移除特定元素,展示如何从数据结构中永久删除项目。
你会收到三个输入:
- 一个表示任务数量的字符串(例如,
"4") - 一个包含任务数据的字符串,格式为:
"name1:status1,name2:status2,name3:status3",其中 status 为"true"或"false"(例如,"Buy groceries:false,Call dentist:true,Finish project:false,Review code:true") - 一个表示要删除的任务索引的字符串(例如,
"1"表示第二个任务,索引从 0 开始)
你的任务是:
- 定义与之前的挑战中相同的
Task结构体,其中包含Name(string)和Completed(bool)字段 - 创建一个名为
removeTask的函数,该函数接收一个由Task结构体组成的切片和一个索引(int)作为参数 - 在
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)
}逻辑与流程中的所有课
自己练习: Go 在线编译器