Creating a Simple Package
Part of the Logic & Flow section of Coddy's GO journey — lesson 53 of 68.
Now it's time to create your own custom package! Creating packages allows you to organize your code into reusable modules that can be imported and used across different programs.
To create a package, you start by declaring it at the top of your file with the package keyword followed by the package name. For our calculator package, we'll use:
package calculatorInside this package, you can define functions, variables, and types. Remember that only exported identifiers (those starting with a capital letter) will be accessible from other packages. Here's how you might define an exported Add function:
package calculator
func Add(a, b int) int {
return a + b
}To use your custom package from another file, you import it just like any other package. From your main package, you can then call the exported functions:
package main
import "calculator"
func main() {
result := calculator.Add(5, 3)
}This modular approach makes your code more organized and allows you to reuse functionality across multiple programs without duplicating code.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a custom mathutils package with basic mathematical operations and then use it from your main program. This challenge will test your ability to create a package, define exported functions, and import your custom package for use in another program.
You will receive two inputs:
- A string containing function definitions in the format
"function1:param1,param2:operation|function2:param1,param2:operation"(e.g.,"Add:5,3:addition|Multiply:4,7:multiplication|Subtract:10,4:subtraction") - A string containing calculation requests in the format
"operation1:value1,value2|operation2:value1,value2|operation3:value1,value2"(e.g.,"Add:15,25|Multiply:6,8|Subtract:50,20")
Your task is to:
- Create a
mathutilspackage by declaringpackage mathutilsat the top - Parse the first input by splitting on pipes (
|) to get individual function definitions - For each function definition, split on colons to get function name, parameters, and operation type
- Create the following exported functions in your
mathutilspackage:Add(a, b int) int- returns the sum of a and bSubtract(a, b int) int- returns a minus bMultiply(a, b int) int- returns the product of a and bDivide(a, b int) int- returns a divided by b (integer division)
- In your main program, import the
mathutilspackage - Display the package information header:
"=== MATHUTILS PACKAGE DEMO ===" - Parse the first input and display the available functions:
"Available functions in mathutils package:"- For each function:
"- [function_name]: Performs [operation_type] on two integers"
- Parse the second input by splitting on pipes to get individual calculation requests
- For each calculation request, split on colons to get the function name and parameters
- Split the parameters on commas to get the two integer values
- Convert the parameter strings to integers using
strconv.Atoi - Display the calculation process header:
"Performing calculations:" - For each calculation request:
- Call the appropriate function from the
mathutilspackage - Display:
"mathutils.[function_name]([param1], [param2]) = [result]"
- Call the appropriate function from the
- Calculate and display summary statistics:
"Calculation Summary:""Total calculations performed: [number_of_calculations]""Functions used: [comma_separated_list_of_unique_function_names_used]""Sum of all results: [sum_of_all_calculation_results]"
- Display package usage confirmation:
"Package demonstration completed successfully""All functions from mathutils package executed correctly"
Use the strings package to split the input strings, the strconv package to convert strings to integers, and the fmt package for formatted output. Remember that only functions starting with capital letters will be exported and accessible from other packages.
Important: Both input lines use pipes (|) as the delimiter between entries. Each entry in the first input has the format FunctionName:param1,param2:operationtype — split on | first, then split each entry on : to extract the function name (index 0) and operation type (index 2).
This challenge demonstrates how to create reusable code through custom packages and how to organize functionality into logical modules.
Cheat sheet
To create a custom package, declare it at the top of your file with the package keyword:
package calculatorOnly exported identifiers (starting with a capital letter) are accessible from other packages:
package calculator
func Add(a, b int) int {
return a + b
}Import and use your custom package from another file:
package main
import "calculator"
func main() {
result := calculator.Add(5, 3)
}This modular approach organizes code and allows reuse across multiple programs without duplicating code.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// TODO: Create your mathutils package functions here
// Since we can't use separate files, define the functions directly
// These would normally be in a separate package file
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
functionDefs := scanner.Text()
scanner.Scan()
calcRequests := scanner.Text()
// TODO: Write your code below
// 1. Define Add, Subtract, Multiply, Divide functions (simulating mathutils package)
// 2. Parse functionDefs: split by '|' to get each definition, then split each by ':'
// Format: FuncName:param1,param2:operation (e.g. "Add:5,3:addition")
// 3. Display package information and available functions
// 4. Parse calcRequests (split by '|'), perform calculations
// 5. Display results and summary statistics
// Suppress unused variable warnings
_ = functionDefs
_ = calcRequests
_ = fmt.Sprintf
_ = strconv.Atoi
_ = strings.Split
// Remember to output the required format as specified in the challenge
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors6Idiomatic Go: Sets
The Set Idiom in GoCreating a SetAdding to a SetChecking for MembershipRemoving from a SetIterating Over a SetRecap - Unique Usernames9Packages and Scope
What is a Package?Exported vs UnexportedCreating a Simple PackagePackage AliasingThe Blank Identifier `_`The `init` functionRecap - Building a Utility