YouTube Summaries | Beginners Should Think Differently When Writing Golang

October 21st, 2023

TL;DW:

  • This video covers transitioning to Go (Golang) from other languages, emphasizing its data-centric approach.
  • Demonstrates creating a “book” structure and manipulating data through functions.
  • Highlights the importance of using pointers for data modification.
  • Method receivers in Go provide an object-oriented appearance.
  • Go focuses on data, structures, and functions, necessitating a different mindset compared to traditional object-oriented languages.

Go as a Data-Centric Language

  • Go encourages developers to think of everything as data.
  • Structures in Go are not objects; they are collections of data fields.

Data Manipulation in Go

  • Data manipulation in Go is primarily done through functions.
  • The video shows how to modify data within a structure using functions.

Importance of Pointers

  • Pointers are essential for modifying the actual data within a structure.
  • The video explains that without pointers, only copies of the data are modified, leading to data loss.

Method Receivers in Go

  • Go allows for method receivers to make the code appear more object-oriented, even though Go lacks traditional objects.

An example book structure with a saveBook method

##Go Code: "book" Structure and "saveBook" Method

import (
    "fmt"
    "time"
)

// Define the "book" structure.
type book struct {
    title     string
    author    string
    numPages  int
    isSaved   bool
    savedAt   time.Time
}

// Define a method to save the book.
func (b *book) saveBook() {
    b.isSaved = true
    b.savedAt = time.Now()
}

func main() {
    // Create a new book instance.
    myBook := &book{
        title:    "Golang for Beginners",
        author:   "John Doe",
        numPages: 200,
        isSaved:  false,
    }

    // Print the initial state of the book.
    fmt.Printf("Book Title: %s\nAuthor: %s\nNumber of Pages: %d\nIs Saved: %t\nSaved At: %s\n",
        myBook.title, myBook.author, myBook.numPages, myBook.isSaved, myBook.savedAt)

    // Call the saveBook method to save the book.
    myBook.saveBook()

    // Print the updated state of the book.
    fmt.Printf("\nBook Title: %s\nAuthor: %s\nNumber of Pages: %d\nIs Saved: %t\nSaved At: %s\n",
        myBook.title, myBook.author, myBook.numPages, myBook.isSaved, myBook.savedAt)
}