安裝使用的外部函式庫
去取得 github.com/aquasecurity/table
目錄結構
主機程式
package main func main() { todos := Todos{} storage := NewStorage[Todos]("todos.json") storage.Load(&todos) CmdFlags := NewCmdflags() CmdFlags.Execute(&todos) storage.Save(todos) }
- 建立結構名稱為 Todos 的切片
- 在先前使用 storage.Save 建立的「todo.json」檔案中為系統中現有的待辦事項建立動態記憶體
- 如果沒有,它將載入為空
- 解析並驗證使用者提供的命令標誌
- 依照提供的標誌執行
功能實現
package main import ( "errors" "fmt" "os" "strconv" "time" "github.com/aquasecurity/table" ) type Todo struct { Title string Completed bool CreatedAt time.Time // this field here is a pointer reference because it can be null CompletedAt *time.Time } // a slice(array) of Todo type Todos []Todo // Passing Todo slice here as a reference // declares a parameter named todos that is a pointer to a Todos slice. // the function receives a copy of the slice under the name todos func (todos *Todos) add(title string) { todo := Todo{ Title: title, Completed: false, CompletedAt: nil, CreatedAt: time.Now(), } *todos = append(*todos, todo) } func (todos *Todos) validateIndex(index int) error { if index = len(*todos) { err := errors.New("invalid index") fmt.Println(err) } return nil } func (todos *Todos) delete(index int) error { t := *todos if err := t.validateIndex(index); err != nil { return err } *todos = append(t[:index], t[index+1:]...) return nil } func (todos *Todos) toggle(index int) error { t := *todos if err := t.validateIndex(index); err != nil { return err } isCompleted := t[index].Completed if !isCompleted { completionTime := time.Now() t[index].CompletedAt = &completionTime } t[index].Completed = !isCompleted return nil } func (todos *Todos) edit(index int, title string) error { t := *todos if err := t.validateIndex(index); err != nil { return err } t[index].Title = title return nil } func (todos *Todos) print() { table := table.New(os.Stdout) table.SetRowLines(false) table.SetHeaders("#", "Title", "Status", "Created", "Completed") for index, t := range *todos { mark := "❌" completedAt := "" if t.Completed { mark = "✅" if t.CompletedAt != nil { completedAt = t.CompletedAt.Format(time.RFC1123) } } table.AddRow(strconv.Itoa(index), t.Title, mark, t.CreatedAt.Format(time.RFC1123), completedAt) } table.Render() }
儲存實現
package main import ( "encoding/json" "os" ) type Storage[T any] struct { FileName string } func NewStorage[T any](filename string) *Storage[T] { return &Storage[T]{FileName: filename} } func (s *Storage[T]) Save(data T) error { fileData, err := json.MarshalIndent(data, "", "\t") if err != nil { return err } return os.WriteFile(s.FileName, fileData, 0644) } func (s *Storage[T]) Load(data *T) error { fileData, err := os.ReadFile(s.FileName) if err != nil { return err } return json.Unmarshal(fileData, data) }
命令列標誌驗證和執行
package main import ( "flag" "fmt" "os" "strconv" "strings" ) type CmdFlags struct { Help bool Add string Del int Edit string Update int List bool } func NewCmdflags() *CmdFlags { cf := CmdFlags{} flag.BoolVar(&cf.Help, "help", false, "List existing commands") flag.StringVar(&cf.Add, "add", "", "Add a new todo specify title") flag.StringVar(&cf.Edit, "edit", "", "Edit an existing todo, enter #index and specify a new title. \"id:new title\"") flag.IntVar(&cf.Del, "del", -1, "Specify a todo by #index to delete") flag.IntVar(&cf.Update, "update", -1, "Specify a todo #index to update") flag.BoolVar(&cf.List, "list", false, "List all todos") for _, arg := range os.Args[1:] { if strings.HasPrefix(arg, "-") && !isValidFlag(arg) { fmt.Printf("Unknown flag: %s\n", arg) fmt.Println("try --help to know more") os.Exit(0) } } flag.Parse() return &cf } func isValidFlag(flag string) bool { validFlags := []string{ "-help", "--help", "-add", "--add", "-edit", "--edit", "-del", "--del", "-update", "--update", "-list", "--list", } if idx := strings.Index(flag, "="); idx != -1 { flag = flag[:idx] } for _, validFlag := range validFlags { if flag == validFlag { return true } } return false } func (cf *CmdFlags) Execute(todos *Todos) { switch { case cf.List: todos.print() case cf.Add != "": todos.add(cf.Add) case cf.Edit != "": parts := strings.SplitN(cf.Edit, ":", 2) if len(parts) != 2 { fmt.Printf("Error, invalid format for edit.\nCorrect Format: \"id:new title\" ") os.Exit(1) } index, err := strconv.Atoi(parts[0]) if err != nil { fmt.Printf("Error, Invalid index for edit") os.Exit(1) } todos.edit(index, parts[1]) case cf.Update != -1: todos.toggle(cf.Update) case cf.Del != -1: todos.delete(cf.Del) case cf.Help: fmt.Println("usage:") fmt.Println("--help\t\t| List existing commands") fmt.Println("--add\t\t| Add new task") fmt.Println("--del\t\t| Delete an existing task") fmt.Println("--update\t| Check/Uncheck existing task") fmt.Println("--edit\t\t| Edit an existing task") } }
Github 儲存庫: CLI Todo 應用程式
以上是基於 Go CLI 的 Todo 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

在Debian系統上確保整體安全性對於保護LibOffice等應用程序的運行環境至關重要。以下是一些提高系統安全性的通用建議:系統更新定期更新系統以修補已知的安全漏洞。 Debian12.10發布了安全更新,修復了大量安全漏洞,包括一些關鍵軟件包。用戶權限管理避免使用root用戶進行日常操作,以減少潛在的安全風險。建議創建普通用戶並加入sudo組,以限制對系統的直接訪問。 SSH服務安全配置使用SSH密鑰對進行身份認證,禁用root遠程登錄,並限制空密碼登錄。這些措施可以增強SSH服務的安全性,防止

在Debian系統上調整Rust編譯選項,可以通過多種途徑來實現,以下是幾種方法的詳細說明:使用rustup工具進行配置安裝rustup:若你尚未安裝rustup,可使用下述命令進行安裝:curl--proto'=https'--tlsv1.2-sSfhttps://sh.rustup.rs|sh依照提示完成安裝過程。設置編譯選項:rustup可用於為不同的工具鍊和目標配置編譯選項。你可以使用rustupoverride命令為特定項目設置編譯選項。例如,若想為某個項目設置特定的Rust版

在Debian系統上管理Kubernetes(K8S)節點通常涉及以下幾個關鍵步驟:1.安裝和配置Kubernetes組件準備工作:確保所有節點(包括主控節點和工作節點)都已安裝Debian操作系統,並且滿足安裝Kubernetes集群的基本要求,如足夠的CPU、內存和磁盤空間。禁用swap分區:為了確保kubelet能夠順利運行,建議禁用swap分區。設置防火牆規則:允許必要的端口,如kubelet、kube-apiserver、kube-scheduler等使用的端口。安裝container

在Debian上設置Golang環境時,確保系統安全是至關重要的。以下是一些關鍵的安全設置步驟和建議,幫助您構建一個安全的Golang開發環境:安全設置步驟系統更新:在安裝Golang之前,確保系統是最新的。使用以下命令更新系統軟件包列表和已安裝的軟件包:sudoaptupdatesudoaptupgrade-y防火牆配置:安裝並配置防火牆(如iptables)以限制對系統的訪問。僅允許必要的端口(如HTTP、HTTPS和SSH)連接。 sudoaptinstalliptablessud

在Debian上優化和部署Kubernetes集群的性能是一個涉及多個方面的複雜任務。以下是一些關鍵的優化策略和建議:硬件資源優化CPU:確保為Kubernetes節點和Pod分配足夠的CPU資源。內存:增加節點的內存容量,特別是對於內存密集型應用。存儲:使用高性能的SSD存儲,避免使用網絡文件系統(如NFS),因為它們可能會引入延遲。內核參數優化編輯/etc/sysctl.conf文件,添加或修改以下參數:net.core.somaxconn:65535net.ipv4.tcp_max_syn

在Debian系統中,你可以利用cron來安排定時任務,實現Python腳本的自動化執行。首先,啟動終端。通過輸入以下命令,編輯當前用戶的crontab文件:crontab-e如果需要以root權限編輯其他用戶的crontab文件,請使用:sudocrontab-uusername-e將username替換為你要編輯的用戶名。在crontab文件中,你可以添加定時任務,格式如下:*****/path/to/your/python-script.py這五個星號分別代表分鐘(0-59)、小

在Debian系統中調整Golang的網絡參數可以通過多種方式實現,以下是幾種可行的方法:方法一:通過設置環境變量臨時設置環境變量:在終端中輸入以下命令可以臨時設置環境變量,此設置僅在當前會話有效。 exportGODEBUG="gctrace=1netdns=go"其中,gctrace=1會激活垃圾回收跟踪,netdns=go則使Go使用其自身的DNS解析器而非系統默認的。永久設置環境變量:將上述命令添加到你的shell配置文件中,例如~/.bashrc或~/.profile

在Debian系統上自定義LibOffice的快捷鍵可以通過系統設置進行調整。以下是一些常用的步驟和方法來設置LibOffice的快捷鍵:設置LibOffice快捷鍵的基本步驟打開系統設置:在Debian系統中,點擊左上角的菜單(通常是一個齒輪圖標),然後選擇“系統設置”。選擇設備:在系統設置窗口中,選擇“設備”。選擇鍵盤:在設備設置頁面中,選擇“鍵盤”。找到對應工具的命令:在鍵盤設置頁面中,向下滾動到最底部可以看到“快捷鍵”選項,點擊它會彈出一個窗口。在彈出的窗口中找到對應LibOffice工


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!