0
0
Goprogramming~30 mins

Interface definition in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Interface definition
📖 Scenario: You are building a simple program to represent different types of vehicles. Each vehicle can describe itself by returning its type as a string.
🎯 Goal: Create an interface called Vehicle with a method Type() that returns a string. Then create two structs Car and Bike that implement this interface.
📋 What You'll Learn
Create an interface named Vehicle with a method Type() string
Create a struct named Car
Create a struct named Bike
Implement the Type() method for both Car and Bike to return their type as a string
Create variables of type Car and Bike
Use the Vehicle interface to call the Type() method on both variables
Print the results
💡 Why This Matters
🌍 Real World
Interfaces let you write code that works with different types in a uniform way, like handling different vehicles in a transport app.
💼 Career
Understanding interfaces is key for Go developers to build modular, testable, and maintainable software.
Progress0 / 4 steps
1
Create structs for vehicles
Create two structs called Car and Bike with no fields.
Go
Hint

Use the type keyword to define structs with empty braces {}.

2
Define the Vehicle interface
Create an interface called Vehicle with a method Type() string.
Go
Hint

Use type Vehicle interface { Type() string } to define the interface.

3
Implement the Type() method for Car and Bike
Write the Type() method for Car that returns "Car" and for Bike that returns "Bike".
Go
Hint

Define methods with receiver types Car and Bike that return the correct string.

4
Use the Vehicle interface and print results
Create variables myCar of type Car and myBike of type Bike. Then create variables v1 and v2 of type Vehicle assigned to myCar and myBike. Finally, print the results of calling Type() on v1 and v2.
Go
Hint

Use var v1 Vehicle = myCar to assign the struct to the interface variable. Use println() to print the results.