Imports and Paths

In this chapter, we'll explore bring items into scope with use statements.

Imports and Paths

The use statement brings items from other modules into scope, letting you use them without their full path.

Basic Imports

module main
 
use math.add
use math.multiply
 
fn main() -> void {
    let sum = add(5, 3)
    let product = multiply(4, 2)
    println("Sum: ", sum, ", Product: ", product)
}

Without imports, you'd need full paths:

module main
 
fn main() -> void {
    let sum = math.add(5, 3)
    let product = math.multiply(4, 2)
}

Importing Multiple Items

Import several items from the same module:

module main
 
use utils.strings.{trim, uppercase, lowercase}
use math.{add, subtract, multiply, divide}
 
fn main() -> void {
    let text = trim("  hello  ")
    let sum = add(1, 2)
}

Importing Entire Modules

Import all public items with *:

module main
 
use math.*
 
fn main() -> void {
    let a = add(1, 2)
    let b = subtract(5, 3)
    let c = multiply(4, 2)
}

Use sparingly—it can make code harder to understand.

Renaming Imports

Use as to give an import a different name:

module main
 
use utils.strings.uppercase as upper
use graphics.Color as Colour  // British spelling
 
fn main() -> void {
    let text = upper("hello")
    let red = Colour.Red
}

This is useful for:

  • Avoiding name conflicts
  • Shortening long names
  • Matching your preferred naming

Importing Types

Import structs, enums, and traits:

module main
 
use shapes.Circle
use shapes.Rectangle
use colors.Color
use traits.Drawable
 
fn main() -> void {
    let c = Circle { radius: 5.0 }
    let r = Rectangle { width: 10.0, height: 5.0 }
}

Standard Library Imports

The standard library is available via std:

module main
 
use std.io.{println, read_line}
use std.collections.{Vec, HashMap}
use std.fs.{read_file, write_file}
 
fn main() -> void {
    let mut items: Vec<int> = Vec.new()
    items.push(1)
    items.push(2)
}

Common Standard Library Modules

ModuleContents
std.ioInput/output, println, read_line
std.fsFile system operations
std.collectionsVec, HashMap, HashSet
std.stringString utilities
std.mathMath functions

Import Organization

Keep imports organized at the top of your file:

module main
 
// Standard library
use std.io.println
use std.collections.Vec
 
// External dependencies
use json.parse
use http.Client
 
// Local modules
use utils.helpers
use models.User
 
fn main() -> void {
    // ...
}

Continue to Multi-File Projects.