You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang Todo项目:实现按标题/序号删除任务的技术求助

问题分析与解决方案

你的核心问题是del分支里的变量n始终是默认值0,完全没读取用户输入的参数,所以不管输入del 1还是del 2,都是删除索引0的元素。另外要实现两种删除方式,得先把list命令改成显示序号,让用户清楚任务和输入值的对应关系。

下面是修复并完善后的代码,同时实现按序号删除和按标题删除:

package main

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

type Todo struct {
	Heading      string
	Text         string
	Creationtime time.Time
	Completed    bool
	LeadTime     time.Time
}

func main() {
	todos := []Todo{}
	scanner := bufio.NewScanner(os.Stdin)

	for {
		fmt.Print("> ") // 加提示符优化交互体验
		scanner.Scan()
		input := scanner.Text()
		if input == "exit" { // 增加退出命令,方便终止程序
			break
		}

		words := strings.Split(input, " ")
		if len(words) == 0 {
			continue
		}

		switch words[0] {
		case "add":
			if len(words) < 2 {
				fmt.Println("用法:add <标题> [内容]")
				continue
			}
			todo := Todo{
				Heading:      words[1],
				Text:         strings.Join(words[2:], " "),
				Creationtime: time.Now(),
				Completed:    false,
			}
			todos = append(todos, todo)
			fmt.Printf("已添加任务:%s\n", todo.Heading)

		case "list":
			if len(todos) == 0 {
				fmt.Println("暂无任务")
				continue
			}
			for i, todo := range todos {
				// 显示1-based序号,和用户输入逻辑对齐
				fmt.Printf("%d. %s %s\n", i+1, todo.Heading, todo.Text)
			}

		case "del":
			if len(words) < 2 {
				fmt.Println("用法:del <序号> 或 del <标题>")
				continue
			}
			target := words[1]

			// 先尝试按序号删除
			index, err := strconv.Atoi(target)
			if err == nil {
				// 用户输入是1-based,转成切片的0-based索引
				sliceIndex := index - 1
				if sliceIndex >= 0 && sliceIndex < len(todos) {
					deletedTodo := todos[sliceIndex]
					todos = append(todos[:sliceIndex], todos[sliceIndex+1:]...)
					fmt.Printf("已删除序号%d的任务:%s\n", index, deletedTodo.Heading)
				} else {
					fmt.Println("序号无效,超出任务范围")
				}
				continue
			}

			// 转整数失败,按标题删除(这里删除所有匹配标题的任务)
			originalLen := len(todos)
			newTodos := []Todo{}
			for _, todo := range todos {
				if todo.Heading != target {
					newTodos = append(newTodos, todo)
				}
			}
			todos = newTodos
			deletedCount := originalLen - len(todos)
			if deletedCount > 0 {
				fmt.Printf("已删除%d个标题为%s的任务\n", deletedCount, target)
			} else {
				fmt.Printf("未找到标题为%s的任务\n", target)
			}

		default:
			fmt.Println("未知命令,支持的命令:add、list、del、exit")
		}
	}
}

关键优化点说明

  1. list命令优化:显示1-based序号,用户能直接对应要删除的任务编号,比如输入del 2就对应列表里的第2项。
  2. del命令参数处理:
    • 先尝试解析用户输入为序号,转成切片的0-based索引后做有效性检查,避免越界panic;
    • 解析失败则按标题删除,遍历切片过滤掉匹配标题的任务,同时给用户反馈删除数量。
  3. 交互体验优化:增加命令提示符、参数错误提示、退出命令,避免无意义的崩溃或困惑。

内容的提问来源于stack exchange,提问作者Nikita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 13:25:00