User Tools

Site Tools


go:love_of_go

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
go:love_of_go [2025/11/17 09:56] v1ctorgo:love_of_go [2025/11/18 10:39] (current) – [ERRORS] v1ctor
Line 85: Line 85:
 ==== ERRORS ==== ==== ERRORS ====
  
-Creating custom error:+Go has type to communicate errors - **error**. Example usage:
 <code go> <code go>
-return 0, errors.New("division by zero not allowed")+func (book *Book) SetCopies(copies int) error { 
 +  if copies < 
 +    return fmt.Errorf("negative number of copies: %d"copies) 
 +  } 
 +  book.Copies = copies 
 +  return nil 
 +
 +</code> 
 + 
 +<code go> 
 +err := book.SetCopies(-1) 
 +if err != nil { 
 +  fmt.Println("Oh dear, something went wrong:", err) 
 +}
 </code> </code>
  
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:
 } }
 </code> </code>
 +
 +==== POINTERS ====
 +
 +<code go>
 +x := 5
 +y := &          // `y` is a pointer to `x`. `&` is an address operator
 + 
 +fmt.Println(*y)   // *y dereferences y - it retrieves the value that y “points” to
 +</code> 
  
 ==== OBJECTS ==== ==== OBJECTS ====
Line 247: Line 270:
     book.Title, book.Author, book.Copies)     book.Title, book.Author, book.Copies)
 } }
 +</code>
 +
 +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                    // only affects local `book`, not the original
 +}
 +</code>
 +
 +And the //pointer// example:
 +<code go>
 +func (book *Book) SetCopies(copies int) {
 + book.Copies = copies               // Go provides an automatic de-referencing when we use
 +                                           // 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)                         // That's here, when we pass `value` or `reference` to
 +                                           // the method
 +
 </code> </code>
go/love_of_go.1763373405.txt.gz · Last modified: by v1ctor