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/18 09:38] – [COMMA, OK PATTERN] 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 224: Line 237:
 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.
  
-==== 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>  
  
 ==== COMMA, OK PATTERN ==== ==== COMMA, OK PATTERN ====
Line 247: 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 267: Line 281:
   book.Copies = copies                    // only affects local `book`, not the original   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.1763458739.txt.gz · Last modified: by v1ctor