Menu
Coddy logo textTech

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 icon

Challenge

Medium

Fix the import statement in utils.go so the functions work correctly. You need to import the strings and math packages:

  • FormatText uses strings.ToUpper
  • ContainsWord uses strings.Contains
  • SquareRoot uses math.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))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming