windjammer 0.48.0

A simple language inspired by Go, Ruby, and Elixir that transpiles to Rust - 80% of Rust's power with 20% of the complexity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# Getting Started with Windjammer

**Welcome to Windjammer!** This tutorial will get you up and running in 15 minutes.

---

## What is Windjammer?

Windjammer is a **systems programming language** that gives you:
- **80% of Rust's power** with **20% of Rust's complexity**
-**Memory safety** without garbage collection
-**Performance** matching Rust (98.7% measured)
-**Simple syntax** inspired by Rust, Python, and Go
-**100% Rust crate compatibility** (transpiles to Rust)

**Perfect for**: Web APIs, CLI tools, system utilities, microservices

---

## Installation

### Prerequisites
- Rust 1.70+ (Windjammer transpiles to Rust)
- Git

### Install Windjammer CLI

```bash
cargo install windjammer
```

Or build from source:

```bash
git clone https://github.com/windjammer-lang/windjammer
cd windjammer
cargo build --release
cargo install --path .
```

### Verify Installation

```bash
wj --version
# Output: windjammer 0.23.0
```

---

## Your First Program

### Hello World

Create `hello.wj`:

```windjammer
fn main() {
    println!("Hello, Windjammer!")
}
```

**Run it:**

```bash
wj run hello.wj
```

**That's it!** No project setup needed for simple scripts.

---

## Your First Project

### Create a New Project

```bash
wj new my_app
cd my_app
```

This creates:
```
my_app/
├── wj.toml          # Project configuration
├── src/
│   └── main.wj      # Your code
└── Cargo.toml       # Generated Rust config (auto-managed)
```

### Project Structure

**`wj.toml`** - Windjammer's native config:
```toml
[package]
name = "my_app"
version = "0.1.0"

[compiler]
defer_drop = true
defer_drop_threshold = 1024

[dependencies]
# Windjammer dependencies here
```

**`src/main.wj`** - Your code:
```windjammer
fn main() {
    println!("Welcome to my app!")
}
```

### Build and Run

```bash
wj run              # Run your app
wj build            # Build (generates Rust, compiles)
wj test             # Run tests
wj fmt              # Format code
wj lint             # Lint code (uses clippy)
```

---

## Language Basics

### Variables

```windjammer
// Immutable by default (like Rust)
let x = 42
let name = "Alice"

// Mutable when needed
let mut count = 0
count += 1

// Type inference (but explicit types allowed)
let age: int = 30
let pi: float = 3.14
```

### Functions

```windjammer
// Simple function
fn greet(name: string) {
    println!("Hello, ${name}!")
}

// With return type
fn add(a: int, b: int) -> int {
    a + b  // No 'return' needed for last expression
}

// With explicit return
fn is_even(n: int) -> bool {
    return n % 2 == 0
}
```

### String Interpolation

```windjammer
let name = "Bob"
let age = 25

// Built-in interpolation (no format! macro needed)
println!("${name} is ${age} years old")
println!("Next year: ${age + 1}")
```

### Control Flow

```windjammer
// If/else
if age >= 18 {
    println!("Adult")
} else {
    println!("Minor")
}

// Match (pattern matching)
match status {
    "active" => println!("Running"),
    "idle" => println!("Waiting"),
    _ => println!("Unknown"),
}

// Match with values
let message = match count {
    0 => "none",
    1 => "one",
    _ => "many",
}

// Loops
for i in 0..10 {
    println!("${i}")
}

let mut x = 0
while x < 5 {
    x += 1
}
```

### Collections

```windjammer
// Vectors
let numbers = vec![1, 2, 3, 4, 5]
numbers.push(6)

// HashMap
use std::collections.HashMap

let mut scores = HashMap::new()
scores.insert("Alice", 100)
scores.insert("Bob", 85)

// Iteration
for num in numbers {
    println!("${num}")
}

for (name, score) in scores {
    println!("${name}: ${score}")
}
```

### Structs

```windjammer
// Define a struct
@derive(Debug, Clone)]
struct User {
    name: string,
    age: int,
    email: string,
}

// Create an instance
let user = User {
    name: "Alice",
    age: 30,
    email: "alice@example.com",
}

// Access fields
println!("${user.name} is ${user.age}")

// Methods
impl User {
    pub fn new(name: string, age: int, email: string) -> Self {
        User { name, age, email }
    }
    
    pub fn greet(self) {
        println!("Hi, I'm ${self.name}!")
    }
}

let user = User::new("Bob", 25, "bob@example.com")
user.greet()
```

### Error Handling

```windjammer
// Result type (like Rust)
fn divide(a: int, b: int) -> Result<int, string> {
    if b == 0 {
        Err("Division by zero")
    } else {
        Ok(a / b)
    }
}

// Using ? operator
fn calculate() -> Result<int, string> {
    let result = divide(10, 2)?
    Ok(result * 2)
}

// Pattern matching on Result
match divide(10, 0) {
    Ok(val) => println!("Result: ${val}"),
    Err(e) => println!("Error: ${e}"),
}
```

---

## Using the Standard Library

Windjammer has a **comprehensive standard library** with proper abstractions:

### File I/O

```windjammer
use std::fs

// Read a file
let contents = fs::read_to_string("data.txt")?

// Write a file
fs::write("output.txt", "Hello, world!")?

// Check if file exists
if fs.exists("config.json") {
    println!("Config found!")
}
```

### JSON

```windjammer
use std::json

@derive(Serialize, Deserialize)]
struct Config {
    host: string,
    port: int,
}

// Serialize
let config = Config { host: "localhost", port: 8080 }
let json = json::stringify(&config)?

// Deserialize
let config: Config = json::parse(json_string)?
```

### HTTP Client

```windjammer
use std::http

@async
fn fetch_data() -> Result<string, Error> {
    let response = http::get("https://api.example.com/data").await?
    Ok(response.text().await?)
}
```

### HTTP Server

```windjammer
use std::http

@async
fn main() {
    http.serve("127.0.0.1:8080", |req| {
        if http.path(req) == "/" {
            http.json_response(200, { "message": "Hello!" })
        } else {
            http.json_response(404, { "error": "Not found" })
        }
    }).await
}
```

---

## Key Differences from Rust

### 1. **No Manual Lifetime Annotations**

**Rust:**
```rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
```

**Windjammer:**
```windjammer
fn longest(x: string, y: string) -> string {
    if x.len() > y.len() { x } else { y }
}
// Compiler infers ownership automatically!
```

### 2. **Automatic Ownership Inference**

**Rust:**
```rust
let x = String::from("hello");
takes_ownership(x);       // Explicit move
// x is invalid here!

let y = String::from("world");
borrows(&y);              // Explicit borrow
// y is still valid
```

**Windjammer:**
```windjammer
let x = "hello"
takes_ownership(x)  // Compiler decides to move
// x is handled correctly

let y = "world"
borrows(y)  // Compiler decides to borrow
// y is still valid
```

### 3. **String Interpolation Built-in**

**Rust:**
```rust
format!("Hello, {}! You are {} years old.", name, age)
```

**Windjammer:**
```windjammer
"Hello, ${name}! You are ${age} years old."
```

### 4. **Simplified Decorators**

**Rust:**
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User { ... }
```

**Windjammer:**
```windjammer
@derive(Debug, Clone, Serialize, Deserialize)]
struct User { ... }
```

---

## Best Practices

### 1. **Let the Compiler Help You**

Windjammer's ownership inference is smart. Trust it:

```windjammer
// ✅ Good - let compiler decide
fn process(data: Vec<int>) {
    for item in data {
        println!("${item}")
    }
}

// ❌ Don't overthink ownership
// Just write what you mean!
```

### 2. **Use the Standard Library**

Don't import crates directly when stdlib has it:

```windjammer
// ✅ Good - uses stdlib
use std::http
use std::json
use std::db

// ❌ Avoid - crate leakage
use axum::Router
use serde_json::Value
```

### 3. **Embrace Pattern Matching**

```windjammer
// ✅ Good - clear and safe
match result {
    Ok(val) => process(val),
    Err(e) => log.error("Failed: ${e}"),
}

// ❌ Avoid - can panic
let val = result.unwrap()
```

### 4. **Use Meaningful Names**

```windjammer
// ✅ Good
let user_count = users.len()
let is_valid = validate_input(data)

// ❌ Avoid
let n = users.len()
let x = validate_input(data)
```

---

## Next Steps

**Tutorials**:
1. **Getting Started** (You are here!)
2. [Building a CLI Tool]./02_CLI_TOOL.md - Create wjfind from scratch
3. [Building a Web API]./03_WEB_API.md - Create a REST API
4. [Building a WebSocket Server]./04_WEBSOCKET.md - Real-time chat

**Documentation**:
- [Language Guide]../GUIDE.md - Complete language reference
- [Standard Library]../stdlib/README.md - All stdlib modules
- [Comparison]../COMPARISON.md - Windjammer vs Rust vs Go
- [Best Practices]../BEST_PRACTICES.md - Production tips

**Examples**:
- [TaskFlow API]../../examples/taskflow/ - Full REST API
- [wjfind]../../examples/wjfind/ - File search CLI tool
- [wschat]../../examples/wschat/ - WebSocket chat server

---

## Getting Help

- **Discord**: [Join our community]https://discord.gg/windjammer
- **GitHub**: [Issues and discussions]https://github.com/windjammer-lang/windjammer
- **Docs**: [Full documentation]https://windjammer-lang.org/docs

---

## Quick Reference

### Commands

```bash
wj new <name>        # Create new project
wj run               # Run your app
wj build             # Build release binary
wj test              # Run tests
wj fmt               # Format code
wj lint              # Lint code
wj update            # Update Windjammer CLI
```

### Common Types

```windjammer
int, float, bool, string
Vec<T>, HashMap<K, V>, HashSet<T>
Option<T>, Result<T, E>
```

### Stdlib Modules

```windjammer
std.fs       // File system
std.http     // HTTP client + server
std.json     // JSON serialization
std.db       // Database
std.log      // Logging
std.time     // Time operations
std.crypto   // Cryptography
std.regex    // Regular expressions
std.cli      // CLI argument parsing
std.thread   // Threading + parallel
```

---

**Welcome to Windjammer! Start building today! 🚀**