Packages & Imports
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 3 of 107.
Every Go file begins with a package declaration. The import keyword brings in packages from Go's standard library so you can use their functions.
Import a single package
import "fmt"Import multiple packages using an import block
import (
"fmt"
"math"
"strings"
)Use functions from imported packages with the package name as prefix
package main
import (
"fmt"
"strings"
"math"
)
func main() {
upper := strings.ToUpper("hello")
fmt.Println(upper) // Output: HELLO
root := math.Sqrt(16)
fmt.Println(root) // Output: 4
}Common standard library packages
"fmt" // Formatted I/O (Print, Scan, Sprintf)
"strings" // String manipulation (ToUpper, Contains, Replace)
"math" // Math functions (Sqrt, Pow, Pi)
"strconv" // String conversions (Itoa, Atoi)You access functions from a package using packagename.FunctionName. Go only lets you import packages you actually use — unused imports cause a compile error.
Challenge
MediumFix the import statement in utils.go so the functions work correctly. You need to import the strings and math packages:
FormatTextusesstrings.ToUpperContainsWordusesstrings.ContainsSquareRootusesmath.Sqrt
Cheat sheet
Every Go file begins with a package declaration. Use the import keyword to bring in packages from Go's standard library.
Import a single package:
import "fmt"Import multiple packages using an import block:
import (
"fmt"
"math"
"strings"
)Access functions from imported packages using packagename.FunctionName:
package main
import (
"fmt"
"strings"
"math"
)
func main() {
upper := strings.ToUpper("hello")
fmt.Println(upper) // Output: HELLO
root := math.Sqrt(16)
fmt.Println(root) // Output: 4
}Common standard library packages:
"fmt" // Formatted I/O (Print, Scan, Sprintf)
"strings" // String manipulation (ToUpper, Contains, Replace)
"math" // Math functions (Sqrt, Pow, Pi)
"strconv" // String conversions (Itoa, Atoi)Note: Go only allows you to import packages you actually use — unused imports cause a compile error.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
line := scanner.Text()
parts := strings.Fields(line)
numStr := parts[len(parts)-1]
text := strings.Join(parts[:len(parts)-1], " ")
num, _ := strconv.ParseFloat(numStr, 64)
fmt.Printf("Upper: %s\n", FormatText(text))
fmt.Printf("Contains 'world': %t\n", ContainsWord(text, "world"))
fmt.Printf("Sqrt: %.2f\n", SquareRoot(num))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool