0
0
Goprogramming~30 mins

Receiver types in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Receiver Types in Go
📖 Scenario: Imagine you are creating a simple program to manage a bank account. You want to add money and check the balance using methods attached to your account.
🎯 Goal: Build a Go program that defines a BankAccount struct and uses both pointer and value receiver methods to modify and read the account balance.
📋 What You'll Learn
Create a struct called BankAccount with a field balance of type float64
Write a method Deposit with a pointer receiver that adds an amount to the balance
Write a method Balance with a value receiver that returns the current balance
Create a main function to demonstrate using both methods
💡 Why This Matters
🌍 Real World
Managing bank accounts or any data where you need to update or read values using methods.
💼 Career
Understanding receiver types is essential for writing clear and efficient Go code, especially in backend development and systems programming.
Progress0 / 4 steps
1
Create the BankAccount struct
Create a struct called BankAccount with a field balance of type float64.
Go
Hint

Use the type keyword to define a struct and add a field named balance with type float64.

2
Add a Deposit method with pointer receiver
Add a method called Deposit with a pointer receiver (acc *BankAccount) that takes a parameter amount float64 and adds it to acc.balance.
Go
Hint

Use a pointer receiver so the method can change the original balance field.

3
Add a Balance method with value receiver
Add a method called Balance with a value receiver (acc BankAccount) that returns the current balance as float64.
Go
Hint

Use a value receiver because this method only reads data and does not modify it.

4
Use the methods in main and print the balance
In the main function, create a variable account of type BankAccount. Call Deposit(100.0) on account. Then print the result of account.Balance().
Go
Hint

Create the account variable, call Deposit with 100.0, then print account.Balance().