Getting Started With V Programming Pdf New ✭ <FULL>

In most languages, variables are mutable (changeable). In V, the default is immutable. This prevents entire classes of bugs.

Code Example (from a fresh PDF):

module main

fn main() // Immutable (default) name := "V User" // name = "New Name" // ERROR: cannot assign to 'name'

// Mutable (explicit)
mut age := 30
age = 31
println('Hello, $name. You are $age.')
// Short-hand declaration (works inside functions only)
count := 10 // type inferred as int

Explanation:

Common Mistake: Using = instead of := for new variables.


module main

import pdf import time

fn generate_invoice(invoice_num string, amount f64) mut doc := pdf.new_document('A4', pdf.Portrait) page := doc.add_page()

// Title
page.set_font('Helvetica-Bold', 18)
page.text('INVOICE', 250, 800)
// Invoice metadata
page.set_font('Helvetica', 10)
page.text('Number: $invoice_num', 50, 750)
page.text('Date: $time.now().yyyymmdd()', 50, 735)
page.text('Amount: $$$amount:.2f', 50, 700)
// Draw separator line
page.draw_line(50, 680, 550, 680)
doc.save('invoice_$invoice_num.pdf') or  panic(err) 
println('Invoice generated.')

fn main() generate_invoice('INV-101', 249.99)

V supports for loops:

for i in 0..5 
    println(i)

Let’s build a file line counter: count_lines.v

import os

fn main() if os.args.len < 2 eprintln('Usage: count_lines <filename>') exit(1) getting started with v programming pdf new

filename := os.args[1]
data := os.read_file(filename) or 
    eprintln('Cannot read file: $err')
    exit(1)
lines := data.split_into_lines()
println('Lines in $filename: $lines.len')

Compile:

v -prod count_lines.v   # production build, small binary

Run:

./count_lines count_lines.v

V uses automatic reference counting and compile-time memory management. Most allocations happen on the stack.

Example:

fn main() {
    mut arr := []string{}
    arr << 'auto'
    arr << 'freed'
} // arr is automatically freed here

V supports if statements:

if x > 5 
    println('x is greater than 5')

In this guide, we've covered the basics of V programming. You've learned how to set up your environment, declare variables, use basic data types, and control structures. Now, it's time to take your skills to the next level:

Happy coding with V!


V avoids exceptions. Instead, it uses ? (optional) and ! (result) types.

fn divide(a, b f64) ?f64 
    if b == 0 
        return error('division by zero')
return a / b

fn main() result := divide(10, 2) or println('Error: $err') return println(result) // 5.0

You can also propagate errors:

fn risky_op() !int 
    return error('fail')

fn main() ! x := risky_op()? println(x) In most languages, variables are mutable (changeable)