Getting Started with Blue
Welcome to Blue Language FYI! This guide will help you get started with the Blue programming language, a modern systems programming language designed for safety, performance, and developer productivity.
What is Blue?
Blue is a modern systems programming language that prioritizes memory safety, performance, and developer experience. It combines the power of low-level systems programming with modern language design principles, making it suitable for everything from operating systems to web services.
Key Features
- Memory Safety: Prevents common bugs like buffer overflows and use-after-free
- Zero-Cost Abstractions: High-level features with no runtime overhead
- Concurrent by Design: Built-in support for safe concurrent programming
- Type Safety: Strong static type system with inference
- Performance: Compiles to efficient native code
- Interoperability: Seamless integration with C and other languages
Design Philosophy
Safety First
Blue prioritizes safety without sacrificing performance. The type system and borrow checker prevent entire classes of bugs at compile time.
Performance
Blue compiles to efficient machine code with minimal runtime overhead. Zero-cost abstractions ensure that high-level code is as fast as hand-optimized low-level code.
Productivity
Modern language features like pattern matching, generics, and type inference make Blue both powerful and pleasant to use.
Concurrency
Blue provides safe concurrent programming primitives that prevent data races and other concurrency bugs.
Installation
Using the Official Installer
macOS and Linux:
curl --proto '=https' --tlsv1.2 -sSf https://install.bluelang.org | sh
Windows: Download the installer from bluelang.org
Using Package Managers
macOS with Homebrew:
brew install blue-lang
Linux (Ubuntu/Debian):
sudo apt update
sudo apt install blue-lang
Arch Linux:
pacman -S blue-lang
Building from Source
git clone https://github.com/blue-lang/blue.git
cd blue
./configure
make
sudo make install
Verify Installation
blue --version
Your First Blue Program
Hello World
Create a file called hello.bl
:
fn main() {
println("Hello, Blue Language FYI!")
}
Compile and run:
blue build hello.bl
./hello
Simple Calculator
fn main() {
let x = 10
let y = 5
println("Addition: {}", x + y)
println("Subtraction: {}", x - y)
println("Multiplication: {}", x * y)
println("Division: {}", x / y)
}
Basic Concepts
Variables and Mutability
fn main() {
// Immutable by default
let x = 5
// Mutable variable
let mut y = 10
y = 15
// Type annotations (optional with inference)
let z: i32 = 20
let pi: f64 = 3.14159
println("x = {}, y = {}, z = {}, pi = {}", x, y, z, pi)
}
Data Types
fn main() {
// Integer types
let small: i8 = 127
let normal: i32 = 2147483647
let big: i64 = 9223372036854775807
// Unsigned integers
let positive: u32 = 42
// Floating point
let precise: f64 = 3.141592653589793
let fast: f32 = 2.718
// Boolean
let is_blue: bool = true
// Character and strings
let letter: char = 'B'
let greeting: str = "Hello, Blue!"
// Arrays
let numbers: [i32; 5] = [1, 2, 3, 4, 5]
let zeros = [0; 10] // Array of 10 zeros
// Tuples
let point: (i32, i32) = (10, 20)
let (x, y) = point // Destructuring
}
Functions
fn add(x: i32, y: i32) -> i32 {
x + y // Expression return (no semicolon)
}
fn greet(name: str) {
println("Hello, {}!", name)
}
fn fibonacci(n: u32) -> u32 {
match n {
0 | 1 => n,
_ => fibonacci(n - 1) + fibonacci(n - 2)
}
}
fn main() {
let result = add(5, 3)
greet("Blue")
println("Fibonacci(10) = {}", fibonacci(10))
}
Control Flow
fn main() {
let number = 7
// If expressions
let description = if number < 5 {
"small"
} else if number < 10 {
"medium"
} else {
"large"
}
// Match expressions (pattern matching)
let message = match number {
1 => "one",
2 | 3 => "two or three",
4..=6 => "four to six",
_ => "something else"
}
// Loops
let mut counter = 0
loop {
counter += 1
if counter == 5 { break }
}
// While loops
while counter > 0 {
println("Counter: {}", counter)
counter -= 1
}
// For loops
for i in 0..5 {
println("Iteration: {}", i)
}
for item in [1, 2, 3, 4, 5] {
println("Item: {}", item)
}
}
Ownership and Borrowing
fn main() {
// Ownership
let s1 = String::from("hello")
let s2 = s1 // s1 is moved to s2, s1 is no longer valid
// Borrowing (references)
let s3 = String::from("world")
let len = calculate_length(&s3) // Borrow s3
println("Length of '{}' is {}", s3, len) // s3 still valid
// Mutable references
let mut s4 = String::from("hello")
change(&mut s4)
println("{}", s4)
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn change(s: &mut String) {
s.push_str(", world!")
}
Structs and Methods
struct Rectangle {
width: f64,
height: f64
}
impl Rectangle {
fn new(width: f64, height: f64) -> Rectangle {
Rectangle { width, height }
}
fn area(&self) -> f64 {
self.width * self.height
}
fn perimeter(&self) -> f64 {
2.0 * (self.width + self.height)
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle::new(10.0, 20.0)
let rect2 = Rectangle::new(5.0, 15.0)
println("Area: {}", rect1.area())
println("Perimeter: {}", rect1.perimeter())
println("Can hold rect2: {}", rect1.can_hold(&rect2))
}
Enums and Pattern Matching
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32)
}
impl Message {
fn process(&self) {
match self {
Message::Quit => println("Quit message"),
Message::Move { x, y } => println("Move to ({}, {})", x, y),
Message::Write(text) => println("Write: {}", text),
Message::ChangeColor(r, g, b) => println("Color: ({}, {}, {})", r, g, b)
}
}
}
fn main() {
let msg1 = Message::Move { x: 10, y: 20 }
let msg2 = Message::Write(String::from("Hello"))
let msg3 = Message::ChangeColor(255, 0, 0)
msg1.process()
msg2.process()
msg3.process()
}
Error Handling
enum Result<T, E> {
Ok(T),
Err(E)
}
fn divide(x: f64, y: f64) -> Result<f64, String> {
if y == 0.0 {
Err(String::from("Division by zero"))
} else {
Ok(x / y)
}
}
fn main() {
match divide(10.0, 2.0) {
Ok(result) => println("Result: {}", result),
Err(error) => println("Error: {}", error)
}
// Using the ? operator for error propagation
let result = divide(10.0, 0.0)?; // Early return on error
println("This won't print")
}
Concurrency
use std::thread
use std::sync::mpsc
fn main() {
// Spawn a new thread
let handle = thread::spawn(|| {
for i in 1..10 {
println("Thread: {}", i)
thread::sleep(Duration::from_millis(100))
}
})
// Main thread work
for i in 1..5 {
println("Main: {}", i)
thread::sleep(Duration::from_millis(50))
}
// Wait for the spawned thread to finish
handle.join().unwrap()
// Message passing
let (tx, rx) = mpsc::channel()
thread::spawn(move || {
let vals = vec!["hello", "from", "thread"]
for val in vals {
tx.send(val).unwrap()
thread::sleep(Duration::from_millis(100))
}
})
for received in rx {
println("Received: {}", received)
}
}
Package Management
Creating a New Project
blue new my_project
cd my_project
Project Structure
my_project/
├── Blue.toml # Package configuration
├── src/
│ └── main.bl # Main source file
├── tests/ # Test files
└── examples/ # Example programs
Blue.toml Configuration
[package]
name = "my_project"
version = "0.1.0"
edition = "2023"
[dependencies]
json = "1.0"
http = "0.5"
[dev-dependencies]
test-utils = "0.2"
Adding Dependencies
blue add json@1.0
blue add http@0.5 --dev
Build and Run
# Build the project
blue build
# Run the project
blue run
# Run with optimizations
blue run --release
# Run tests
blue test
# Generate documentation
blue doc
# Format code
blue fmt
# Lint code
blue lint
Next Steps
Explore these advanced topics:
- Advanced Types - Generics, traits, and lifetimes
- Memory Management - Deep dive into ownership and borrowing
- Concurrency - Async programming and parallel computing
- Unsafe Blue - Low-level programming when needed
- Macros - Metaprogramming and code generation
- FFI - Interoperability with C and other languages
Ecosystem
Popular Libraries
Web Development:
web-server
- High-performance web serverhttp-client
- HTTP client libraryjson
- JSON parsing and serialization
Systems Programming:
os-interface
- Operating system interfacesfile-system
- File system operationsnetworking
- Network programming
Data Processing:
csv
- CSV file processingdatabase
- Database connectivityserialization
- Data serialization formats
Development Tools
- Blue Language Server: IDE support with autocompletion and error checking
- Blue Debugger: Advanced debugging capabilities
- Blue Profiler: Performance analysis and optimization
- Blue Formatter: Automatic code formatting
Resources
- Blue Language Official Site
- Blue Language Reference
- Blue by Example
- The Blue Programming Language Book
- Blue Community Discord
Ready to dive deeper? Check out our comprehensive documentation for detailed guides on all aspects of Blue programming!