Complete API reference for the ShitRust standard library and core modules.
The core library provides fundamental types and functions that form the foundation of the language.
| Type | Description | Examples |
|---|---|---|
int |
Signed integer type | 42, -7, 0 |
float |
Floating-point number | 3.14, -0.5, 2.71e2 |
bool |
Boolean type | true, false |
char |
Single Unicode character | 'A', '1', '\n' |
string |
UTF-8 encoded string | "Hello", "", "Line\nBreak" |
| Function | Description | Example |
|---|---|---|
print(value) |
Prints a value to standard output without a newline | print("Hello") |
println(value) |
Prints a value to standard output with a newline | println("Hello, World!") |
input(prompt) |
Reads a line from standard input with an optional prompt | let name = input("Enter your name: ") |
typeof(value) |
Returns the type of a value as a string | let type = typeof(42) // "int" |
panic(message) |
Terminates the program with an error message | panic("Something went wrong!") |
The standard library provides a comprehensive set of utilities and data structures for everyday programming tasks.
The Result<T, E> type is used for error handling and represents either a success value of type T or an error value of type E.
// Creating Results
let success: Result = Ok(42);
let failure: Result = Err("Something went wrong");
// Methods on Result
if result.is_ok() {
let value = result.unwrap(); // Gets the value (panics if it's an Err)
}
if result.is_err() {
let error = result.unwrap_err(); // Gets the error (panics if it's an Ok)
}
// Pattern matching on Result
match result {
Ok(value) => println("Success: " + value.to_string()),
Err(error) => println("Error: " + error),
}
// Using the ? operator for error propagation
fn process() -> Result {
let value = risky_operation()?; // Returns early if error
return Ok(value * 2);
}
The Option<T> type represents a value that may or may not be present.
// Creating Options
let some_value: Option = Some(42);
let no_value: Option = None;
// Methods on Option
if option.is_some() {
let value = option.unwrap(); // Gets the value (panics if it's None)
}
if option.is_none() {
// Handle the None case
}
// Pattern matching on Option
match option {
Some(value) => println("Value: " + value.to_string()),
None => println("No value present"),
}
// Using unwrap_or to provide a default value
let value = option.unwrap_or(0);
The I/O module provides functions and types for input/output operations.
import io;
// Reading a file
let contents = io.read_file("example.txt");
// Writing to a file
io.write_file("output.txt", "Hello, World!");
// Appending to a file
io.append_file("log.txt", "New log entry");
// Reading a file line by line
for line in io.read_lines("data.txt") {
println(line);
}
// Using the File type for more control
let file = io.File::open("example.txt", "r");
let line = file.read_line();
file.close();
The collections module provides various data structures for storing and manipulating collections of data.
Lists are ordered collections of elements.
// Creating a list
let numbers = [1, 2, 3, 4, 5];
// Accessing elements
let first = numbers[0]; // Indexing starts at 0
let last = numbers[numbers.len() - 1];
// Methods
numbers.push(6); // Add an element at the end
numbers.pop(); // Remove and return the last element
numbers.insert(0, 0); // Insert at a specific index
numbers.remove(2); // Remove at a specific index
let length = numbers.len(); // Get the length
let contains = numbers.contains(3); // Check if element exists
numbers.clear(); // Remove all elements
// Iterating
for number in numbers {
println(number.to_string());
}
Dictionaries are collections of key-value pairs.
// Creating a dictionary
let user = {
"name": "Alice",
"age": 30,
"is_admin": true
};
// Accessing elements
let name = user["name"];
let age = user.get("age"); // Returns an Option
// Methods
user["email"] = "alice@example.com"; // Add or update a key-value pair
user.remove("is_admin"); // Remove a key-value pair
let has_key = user.contains_key("name"); // Check if key exists
let keys = user.keys(); // Get a list of keys
let values = user.values(); // Get a list of values
let length = user.len(); // Get the number of entries
user.clear(); // Remove all entries
// Iterating
for key in user.keys() {
println(key + ": " + user[key].to_string());
}
for (key, value) in user {
println(key + ": " + value.to_string());
}
The math module provides mathematical functions and constants.
import math;
// Constants
let pi = math.PI;
let e = math.E;
// Basic functions
let abs_value = math.abs(-5); // Absolute value
let power = math.pow(2, 8); // Power
let square_root = math.sqrt(16); // Square root
let round_val = math.round(3.7); // Round to nearest integer
let floor_val = math.floor(3.7); // Round down
let ceil_val = math.ceil(3.2); // Round up
// Trigonometric functions
let sin_val = math.sin(math.PI / 2); // Sine
let cos_val = math.cos(math.PI); // Cosine
let tan_val = math.tan(math.PI / 4); // Tangent
// Other functions
let log_val = math.log(100, 10); // Logarithm
let ln_val = math.ln(math.E); // Natural logarithm
let exp_val = math.exp(2); // Exponential
The string module provides functions for working with strings.
import string;
// String creation
let str1 = "Hello";
let str2 = string.from_char_code(65); // "A"
// String operations
let length = str1.len(); // Length in characters
let concat = str1 + ", World!"; // Concatenation
let upper = str1.to_upper(); // Convert to uppercase
let lower = str1.to_lower(); // Convert to lowercase
let char_at = str1[0]; // Get character at index
let substring = str1.substring(1, 3); // Get substring (inclusive, exclusive)
let trimmed = " text ".trim(); // Remove leading/trailing whitespace
// Searching and replacing
let contains = str1.contains("el"); // Check if contains substring
let starts_with = str1.starts_with("He"); // Check if starts with substring
let ends_with = str1.ends_with("lo"); // Check if ends with substring
let index = str1.index_of("l"); // Find index of first occurrence
let last_index = str1.last_index_of("l"); // Find index of last occurrence
let replaced = str1.replace("l", "L"); // Replace all occurrences
// Splitting and joining
let parts = "a,b,c".split(","); // Split into array
let joined = string.join(["a", "b", "c"], "-"); // Join array with delimiter
The thread module provides facilities for concurrent and parallel programming.
import thread;
// Creating threads
let handle = thread.spawn(fn() -> void {
println("Hello from thread!");
});
// Waiting for threads to finish
handle.join();
// Thread sleep
thread.sleep(1000); // Sleep for 1000 milliseconds
// Using a mutex for thread synchronization
let mutex = thread.Mutex::new(0);
let handle1 = thread.spawn(fn() -> void {
let mut value = mutex.lock();
*value = *value + 1;
});
let handle2 = thread.spawn(fn() -> void {
let mut value = mutex.lock();
*value = *value + 1;
});
handle1.join();
handle2.join();
let final_value = *mutex.lock(); // 2
The time module provides functions for working with dates and times.
import time;
// Getting current time
let now = time.now();
let timestamp = time.timestamp(); // Unix timestamp in seconds
// Creating time from components
let date = time.Date::new(2023, 1, 31);
let date_time = time.DateTime::new(2023, 1, 31, 12, 30, 0);
// Formatting dates
let formatted = date.format("%Y-%m-%d"); // "2023-01-31"
// Parsing dates
let parsed = time.parse("2023-01-31", "%Y-%m-%d");
// Date/time operations
let tomorrow = date.add_days(1);
let next_month = date.add_months(1);
let next_year = date.add_years(1);
let diff = date_time - time.now(); // Time difference in seconds
// Getting components
let year = date.year();
let month = date.month();
let day = date.day();
let hour = date_time.hour();
let minute = date_time.minute();
let second = date_time.second();
let weekday = date.weekday(); // 0 = Sunday, 6 = Saturday