Menu
Coddy logo textTech

Defining Methods on Structs

Part of the Logic & Flow section of Coddy's GO journey — lesson 6 of 68.

In Go, a method is a function that belongs to a specific type. Unlike regular functions that stand alone, methods are attached to structs and allow you to define behavior for your custom data types.

To define a method, you place a receiver between the func keyword and the method name. The receiver specifies which type the method belongs to.

type Person struct {
    Name string
    Age  int
}

func (p Person) greet() {
    fmt.Printf("Hello, my name is %s\n", p.Name)
}

In this example, (p Person) is the receiver, making greet a method of the Person type. The variable p represents the instance of Person that the method is called on, similar to this in other languages.

You can then call the method using dot notation on any Person instance, giving your structs the ability to perform actions related to their data.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

In this challenge, you'll practice defining methods on structs by creating a simple book management system. You'll create a Book struct and define methods that allow the book to display its information.

Important Note: Since book titles and author names may contain spaces, you'll need to use bufio.Scanner to read entire lines of input. The fmt.Scanln function stops reading at the first space, which would break multi-word titles and author names. Use bufio.NewScanner(os.Stdin) and call scanner.Scan() followed by scanner.Text() to read complete lines.

You will receive three inputs:

  • A string representing the book title (e.g., "The Go Programming Language")
  • A string representing the author name (e.g., "Alan Donovan")
  • A string representing the number of pages (e.g., "380")

Your task is to:

  1. Define a Book struct with three fields: Title (string), Author (string), and Pages (int)
  2. Create a method called displayInfo with a value receiver that prints the book information in the format: "Title: [title], Author: [author], Pages: [pages]"
  3. Create a method called getDescription with a value receiver that returns a string in the format: "[title] by [author]"
  4. Use bufio.Scanner to read the input lines properly:
    • Create a scanner: scanner := bufio.NewScanner(os.Stdin)
    • For each input line: call scanner.Scan() then scanner.Text()
    • This ensures titles and author names with spaces are read correctly
  5. Parse the inputs to create a Book instance
  6. Call the displayInfo method to print the book information
  7. Call the getDescription method and print the returned description

The methods should use the receiver variable to access the struct fields and perform their respective operations. Remember that methods with value receivers work with a copy of the struct instance.

Cheat sheet

Methods in Go are functions that belong to a specific type. They are defined with a receiver between the func keyword and method name:

type Person struct {
    Name string
    Age  int
}

func (p Person) greet() {
    fmt.Printf("Hello, my name is %s\n", p.Name)
}

The receiver (p Person) makes greet a method of the Person type. The variable p represents the instance the method is called on.

Methods are called using dot notation on struct instances, allowing structs to perform actions related to their data.

Try it yourself

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

// TODO: Define your Book struct here

// TODO: Define your displayInfo method here

// TODO: Define your getDescription method here

func main() {
    // Create scanner for reading input lines
    scanner := bufio.NewScanner(os.Stdin)
    
    // Read title
    scanner.Scan()
    title := scanner.Text()
    
    // Read author
    scanner.Scan()
    author := scanner.Text()
    
    // Read pages
    scanner.Scan()
    pagesStr := scanner.Text()
    
    // Convert pages string to integer
    pages, _ := strconv.Atoi(pagesStr)
    
    // TODO: Create a Book instance and call the methods
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow