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/17 09:56] – 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 223: | Line 236: | ||
| Instead, we can create a **struct** type, with a field of type we want. | Instead, we can create a **struct** type, with a field of type we want. | ||
| + | |||
| ==== COMMA, OK PATTERN ==== | ==== COMMA, OK PATTERN ==== | ||
| Line 238: | Line 252: | ||
| } | } | ||
| </ | </ | ||
| + | |||
| + | ==== POINTERS ==== | ||
| + | |||
| + | <code go> | ||
| + | x := 5 | ||
| + | y := & | ||
| + | |||
| + | fmt.Println(*y) | ||
| + | </ | ||
| ==== OBJECTS ==== | ==== OBJECTS ==== | ||
| Line 247: | Line 270: | ||
| book.Title, book.Author, | book.Title, book.Author, | ||
| } | } | ||
| + | </ | ||
| + | |||
| + | There are two types of receivers - **Value** and **Pointer** receivers. Think of it as //how the function gets access to the object:// | ||
| + | * By Copy (value receiver) - this **copies the data** into the method | ||
| + | * By Value (pointer receiver) - this gives the method a **reference to the original object** | ||
| + | |||
| + | |||
| + | <code go> | ||
| + | func (book Book) SetCopies(copies int) { | ||
| + | book.Copies = copies | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | And the //pointer// example: | ||
| + | <code go> | ||
| + | func (book *Book) SetCopies(copies int) { | ||
| + | book.Copies = copies | ||
| + | // pointers to struct. Pointers can't have fields, so there | ||
| + | // is no ambiguity here. Otherwise it would look like: | ||
| + | // (*book).Copies = copies | ||
| + | } | ||
| + | |||
| + | book := books.Book{ | ||
| + | Copies: 5, | ||
| + | } | ||
| + | |||
| + | book.SetCopies(12) | ||
| + | // the method | ||
| + | |||
| </ | </ | ||
go/love_of_go.1763373405.txt.gz · Last modified: by v1ctor
