Menu
Coddy logo textTech

Recap - Shapes and Behaviors

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

challenge icon

Challenge

Easy

In this challenge, you'll create a communication system that demonstrates polymorphism through interfaces. You'll build a Speaker interface and implement it with different types that can "speak" in their own unique ways.

You will receive three inputs:

  • A string representing the number of speakers to create (e.g., "3")
  • A string containing speaker types separated by commas (e.g., "person,parrot,person")
  • A string containing speaker names separated by commas (e.g., "Alice,Polly,Bob")

Your task is to:

  1. Define a Speaker interface with one method signature: Speak() that returns a string
  2. Define a Person struct with a Name field (string)
  3. Define a Parrot struct with a Name field (string)
  4. Implement the Speak() method for both structs:
    • Person should return: "Hello, I'm [name]"
    • Parrot should return: "Squawk! [name] says hello!"
  5. Create a function called makeAllSpeak that takes a slice of Speaker interfaces as a parameter
  6. Inside makeAllSpeak, iterate through the slice and call the Speak() method on each speaker, printing the result
  7. Parse the inputs to create the appropriate speaker instances based on the types and names provided
  8. Store all speakers in a slice of Speaker interfaces
  9. Call makeAllSpeak with your slice of speakers

The speakers should be created in the order they appear in the input. For example, if the types are "person,parrot,person" and names are "Alice,Polly,Bob", create a Person named Alice, then a Parrot named Polly, then a Person named Bob. This challenge demonstrates how different types can be treated uniformly through a shared interface, showcasing the power of polymorphism in Go.

Try it yourself

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	// Read input
	var numSpeakersStr string
	var speakerTypesStr string
	var speakerNamesStr string
	
	fmt.Scanln(&numSpeakersStr)
	fmt.Scanln(&speakerTypesStr)
	fmt.Scanln(&speakerNamesStr)
	
	// Parse input
	numSpeakers, _ := strconv.Atoi(numSpeakersStr)
	speakerTypes := strings.Split(speakerTypesStr, ",")
	speakerNames := strings.Split(speakerNamesStr, ",")
	
	// TODO: Write your code below
	// 1. Define the Speaker interface
	// 2. Define Person and Parrot structs
	// 3. Implement Speak() methods for both structs
	// 4. Create makeAllSpeak function
	// 5. Create speakers based on input and store in a slice
	// 6. Call makeAllSpeak with your slice
	
}

All lessons in Logic & Flow