Hone logo
Hone
Problems

Go Value Receiver: Implementing a Flexible Data Processor

This challenge focuses on building a robust and flexible value receiver in Go. You will create a function that can accept various data types and process them based on their underlying structure, demonstrating effective use of Go's type system and interfaces. This skill is crucial for building adaptable APIs and handling diverse data inputs.

Problem Description

Your task is to implement a function ProcessValue that accepts a single argument of type interface{}. This function should be able to handle and process specific data types: int, string, and a custom struct type named Message.

The ProcessValue function should exhibit the following behavior:

  1. Handle int: If the input is an int, print its value along with a descriptive label.
  2. Handle string: If the input is a string, print its value along with a descriptive label.
  3. Handle Message struct: If the input is a Message struct, print its Content field along with a descriptive label.
  4. Handle unknown types: If the input is of any other type, print a message indicating that the type is not supported.

You will also need to define the Message struct.

Key Requirements:

  • The ProcessValue function must accept interface{}.
  • Use Go's type assertion or type switch to determine the concrete type of the received value.
  • Print output to standard output (e.g., using fmt.Println).

Expected Behavior:

The function should gracefully handle all specified types and report unsupported types. The output format should be clear and indicate the type of data being processed.

Edge Cases:

  • Consider what happens when nil is passed as input. (While not explicitly required for int, string, or Message, a robust receiver might handle nil.) For this challenge, assume nil falls under "unknown types."

Examples

Example 1:

Input: 42 (type int)
Output: Received an integer: 42

Example 2:

Input: "Hello, Go!" (type string)
Output: Received a string: Hello, Go!

Example 3:

Input: Message{Content: "Important data"} (type Message struct)
Output: Received a Message struct with content: Important data

Example 4:

Input: 3.14 (type float64)
Output: Unsupported type: float64

Constraints

  • The ProcessValue function must be implemented as a standalone function.
  • The Message struct must have a field named Content of type string.
  • Standard Go libraries (e.g., fmt) are permitted.
  • Performance is not a primary concern for this specific challenge, but the solution should be efficient for its purpose.

Notes

This challenge is an excellent opportunity to practice Go's dynamic typing features within a statically typed language. Think about the most idiomatic way to handle multiple distinct types within a single function. A type switch is often a very clear and readable solution for this scenario.

Loading editor...
go