Skip to content

Instantly share code, notes, and snippets.

@bswen

bswen/.go

Created Mar 9, 2021
Embed
What would you like to do?
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