Hone logo
Hone
Problems

Defining Custom Types in Go

Go's type system allows you to define your own custom types based on existing ones. This is a powerful feature for creating more expressive and maintainable code by giving specific names to data with particular meanings. This challenge will test your understanding of how to define and use custom types in Go.

Problem Description

Your task is to create a Go program that defines and utilizes custom types for representing a UserID and a ProductName. You will then implement a function that takes a UserID and a ProductName and returns a formatted string indicating a product has been assigned to a user.

Key Requirements:

  1. Define UserID Type: Create a new type named UserID that is an alias for int.
  2. Define ProductName Type: Create a new type named ProductName that is an alias for string.
  3. Implement Assignment Function: Create a function AssignProduct that accepts two arguments:
    • userID: of type UserID
    • productName: of type ProductName
    • This function should return a string.
  4. Formatted Output: The AssignProduct function should return a string in the format: "User [UserID] has been assigned product: [ProductName]".

Expected Behavior:

When AssignProduct is called with valid UserID and ProductName values, it should return the correctly formatted string.

Edge Cases to Consider:

  • What happens if UserID is 0 or negative? (While int allows this, for this exercise, we'll assume valid positive int values are passed for UserID as typical identifiers).
  • What happens if ProductName is an empty string?

Examples

Example 1:

Input:
userID = 101
productName = "Laptop"

Output:
"User 101 has been assigned product: Laptop"

Explanation:
The function receives UserID 101 and ProductName "Laptop" and formats them into the specified output string.

Example 2:

Input:
userID = 5
productName = "Keyboard"

Output:
"User 5 has been assigned product: Keyboard"

Explanation:
Demonstrates the function's ability to handle different valid integer and string inputs.

Example 3:

Input:
userID = 20
productName = ""

Output:
"User 20 has been assigned product: "

Explanation:
This shows the expected behavior when the ProductName is an empty string.

Constraints

  • UserID will be a non-negative integer.
  • ProductName will be a string.
  • The AssignProduct function should be efficient and not involve complex computations.

Notes

  • Remember that Go's type system is strict. You cannot directly use an int where a UserID is expected, nor a string where a ProductName is expected, even though they are aliases. You will need to explicitly convert values if you want to use them in contexts requiring the custom type.
  • Consider how you might use these custom types to create more robust code in a larger application, for example, by defining methods on these types. This challenge focuses on the definition and basic usage.
Loading editor...
go