Skip to content

Instantly share code, notes, and snippets.

@bswen
Created March 9, 2021 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bswen/d9d313cfe38bb6c93f63fd9a99672eea to your computer and use it in GitHub Desktop.
Save bswen/d9d313cfe38bb6c93f63fd9a99672eea to your computer and use it in GitHub Desktop.
https://bswen.com/2021/03/others-golang-error1.html how to modify an element in slice when developing golang programs
package main
import (
"errors"
"fmt"
)
type Book struct {
ID uint
Title string
Author string
}
var Books []Book
func init() {
Books = []Book {
Book{
ID: 1,
Title: "aaaaaa",
Author: "jack",
},
Book{
ID: 2,
Title: "bbbbbb",
Author: "mike",
},
}
}
//not work
func ChangeABook1(bookId string,newTitle string)(bool,error) {
defaultResult := false
for _,book:=range Books {
if idstring := fmt.Sprint(book.ID); idstring==bookId {
book.Title = newTitle
return true,nil
}
}
return defaultResult,errors.New("not found "+bookId)
}
func ChangeABook2(bookId string,newTitle string)(bool,error) {
defaultResult := false
for idx,book:=range Books {
if idstring := fmt.Sprint(book.ID); idstring==bookId {
Books[idx].Title = newTitle
return true,nil
}
}
return defaultResult,errors.New("not found "+bookId)
}
func PrintBooks() {
for _,book:=range Books {
fmt.Printf("%v\n",book)
}
}
func main_old() {
book, err := FindABook("1")
if err == nil {
fmt.Printf(" got book %v\n", book)
}else {
fmt.Printf("%v\n",err)
}
}
func main() {
fmt.Print("before change\n")
fmt.Print("===============\n")
PrintBooks()
ChangeABook2("1","newnewnewnnew")
fmt.Print("\nafter change\n")
fmt.Print("===============\n")
PrintBooks()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment