std/io
The std/io module provides functions for console input/output operations.
Import
Section titled “Import”import "std/io";Functions
Section titled “Functions”Print()
Section titled “Print()”fn Print(values: ...Printable)Prints values to stdout without a trailing newline.
import "std/io";
io::Print("Hello ");io::Print("World");io::Print(123);// Output: Hello World123Println()
Section titled “Println()”fn Println(values: ...Printable)Prints values to stdout with a trailing newline. Values are separated by spaces.
import "std/io";
io::Println("Count:", 42);io::Println("Debug:", true, 3.14);// Output:// Count: 42// Debug: true 3.14Read()
Section titled “Read()”fn Read() -> str ! strReads a line from stdin and returns it. Returns an error if input fails.
import "std/io";
io::Print("Enter your name: ");let name := io::Read() catch err { io::Println("Input error:", err); return;};io::Println("Hello,", name);ReadUnsafe()
Section titled “ReadUnsafe()”fn ReadUnsafe() -> strReads a line from stdin without error handling. Returns empty string if input fails.
import "std/io";
let input := io::ReadUnsafe();if len(&(input as []char)) > 0 { io::Println("You entered:", input);}ReadInt()
Section titled “ReadInt()”fn ReadInt() -> str ! i32Reads a line from stdin and parses it as a 32-bit integer.
import "std/io";
io::Print("Enter a number: ");let number := io::ReadInt() catch err { io::Println("Invalid number:", err); return;};io::Println("You entered:", number);ReadFloat()
Section titled “ReadFloat()”fn ReadFloat() -> str ! f64Reads a line from stdin and parses it as a 64-bit floating-point number.
import "std/io";
io::Print("Enter a decimal: ");let decimal := io::ReadFloat() catch err { io::Println("Invalid number:", err); return;};io::Println("You entered:", decimal);Printf()
Section titled “Printf()”fn Printf(fmt: str, args: ...Printable)Prints formatted text using {} placeholders.
import "std/io";
let name := "Alice";let age := 25;io::Printf("Name: {}, Age: {}\n", name, age);// Output: Name: Alice, Age: 25Streaming Interfaces
Section titled “Streaming Interfaces”type Reader interface { Read(maxBytes: i32) -> str ! []byte};
type Writer interface { Write(buf: []byte) -> str ! i32};
type Closer interface { Close()};
type ReadWriter interface { Read(maxBytes: i32) -> str ! []byte, Write(buf: []byte) -> str ! i32};WriteString()
Section titled “WriteString()”fn WriteString(w: Writer, s: str) -> str ! i32Copy()
Section titled “Copy()”fn Copy(dst: Writer, src: Reader, bufSize: i32) -> str ! i64ReadAll()
Section titled “ReadAll()”fn ReadAll(src: Reader, bufSize: i32) -> str ! []byteimport "std/fs";import "std/io";
let file := fs::Create("out.txt") catch err { io::Println("Create error:", err); return;};
defer file.Close();
let w: io::Writer = &mut file;io::WriteString(w, "hello\n") catch err { io::Println("Write error:", err);};Printable Types
Section titled “Printable Types”The following types can be printed using I/O functions:
- Integers:
i8,i16,i32,i64,i128,i256 - Unsigned:
u8,u16,u32,u64,u128,u256 - Floats:
f32,f64,f128,f256 - Text:
str,char,byte - Boolean:
bool
Interactive Programs
Section titled “Interactive Programs”Simple Calculator
Section titled “Simple Calculator”import "std/io";
fn main() { io::Println("Simple Calculator");
io::Print("Enter first number: "); let a := io::ReadInt() catch err { io::Println("Error:", err); return; };
io::Print("Enter operator (+, -, *, /): "); let op := io::Read() catch err { io::Println("Error:", err); return; };
io::Print("Enter second number: "); let b := io::ReadInt() catch err { io::Println("Error:", err); return; };
let result := match op { "+" => a + b, "-" => a - b, "*" => a * b, "/" => if b != 0 { a / b } else { io::Println("Error: Division by zero"); return; }, _ => { io::Println("Error: Unknown operator"); return; } };
io::Printf("{} {} {} = {}\n", a, op, b, result);}Number Guessing Game
Section titled “Number Guessing Game”import "std/io";import "random";
fn main() { let target := random::Range(1, 100); let attempts := 0;
io::Println("Guess the number between 1 and 100!");
while true { attempts += 1; io::Printf("Attempt {}: ", attempts);
let guess := io::ReadInt() catch err { io::Println("Please enter a valid number"); continue; };
if guess == target { io::Printf("Congratulations! You guessed it in {} attempts!\n", attempts); break; } else if guess < target { io::Println("Too low!"); } else { io::Println("Too high!"); } }}Error Handling
Section titled “Error Handling”Input functions return Result types for robust error handling:
import "std/io";
// Method 1: Match expressionlet input := match io::Read() { ok(value) => value, err(msg) => { io::Println("Input failed:", msg); return; }};
// Method 2: Catch syntaxlet number := io::ReadInt() catch err { io::Println("Not a number:", err); -1 // default value};
// Method 3: Error propagationfn getUserInput() -> str ! i32 { io::Print("Enter number: "); let num := io::ReadInt() catch err err; // propagate error return num;}Best Practices
Section titled “Best Practices”- Always handle input errors - Users can enter invalid data
- Use
Printf()for formatted output - More readable than concatenation - Prompt before input - Let users know what you expect
- Validate ranges - Check if numbers are in expected ranges
- Use
ReadUnsafe()sparingly - Only when you’re certain input will be valid
See Also
Section titled “See Also”- Error Handling - Learn about Result types and error handling patterns
- Type System - Understanding type conversions
- Control Flow - Using match expressions for error handling