安裝使用的外部函式庫
去取得 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中文網其他相關文章!

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

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

Dreamweaver Mac版
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。