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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyIn 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:
- Define a
Bookstruct with three fields:Title(string),Author(string), andPages(int) - Create a method called
displayInfowith a value receiver that prints the book information in the format:"Title: [title], Author: [author], Pages: [pages]" - Create a method called
getDescriptionwith a value receiver that returns a string in the format:"[title] by [author]" - Use
bufio.Scannerto read the input lines properly:- Create a scanner:
scanner := bufio.NewScanner(os.Stdin) - For each input line: call
scanner.Scan()thenscanner.Text() - This ensures titles and author names with spaces are read correctly
- Create a scanner:
- Parse the inputs to create a
Bookinstance - Call the
displayInfomethod to print the book information - Call the
getDescriptionmethod 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors