go:love_of_go
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| go:love_of_go [2025/11/18 09:46] – [OBJECTS] v1ctor | go:love_of_go [2025/11/18 10:39] (current) – [ERRORS] v1ctor | ||
|---|---|---|---|
| Line 85: | Line 85: | ||
| ==== ERRORS ==== | ==== ERRORS ==== | ||
| - | Creating | + | Go has a type to communicate errors - **error**. Example usage: |
| <code go> | <code go> | ||
| - | return | + | func (book *Book) SetCopies(copies int) error { |
| + | if copies < 0 { | ||
| + | return fmt.Errorf(" | ||
| + | } | ||
| + | book.Copies = copies | ||
| + | return nil | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | <code go> | ||
| + | err := book.SetCopies(-1) | ||
| + | if err != nil { | ||
| + | fmt.Println("Oh dear, something went wrong:", err) | ||
| + | } | ||
| </ | </ | ||
| Line 270: | Line 283: | ||
| </ | </ | ||
| - | The the //pointer// example: | + | And the //pointer// example: |
| <code go> | <code go> | ||
| func (book *Book) SetCopies(copies int) { | func (book *Book) SetCopies(copies int) { | ||
| Line 278: | Line 291: | ||
| // (*book).Copies = copies | // (*book).Copies = copies | ||
| } | } | ||
| + | |||
| + | book := books.Book{ | ||
| + | Copies: 5, | ||
| + | } | ||
| + | |||
| + | book.SetCopies(12) | ||
| + | // the method | ||
| + | |||
| </ | </ | ||
go/love_of_go.1763459175.txt.gz · Last modified: by v1ctor
