NATIVE FOUNDATIONS
Native foundations
Pass an input to a small function and add 42. The program keeps the syntax easy to follow.
Read the guide# Add a fixed amount to the input.
func entry(value: i32) -> i32:
return value + 42LET THE CODE SPEAK
Choose a topic to explore complete VOID source, its expected result or application status, and the idea behind it. These are source examples; public compiler builds are not yet available.
NATIVE FOUNDATIONS
Pass an input to a small function and add 42. The program keeps the syntax easy to follow.
Read the guide# Add a fixed amount to the input.
func entry(value: i32) -> i32:
return value + 42FUNCTIONS & RECURSION
Calculate a factorial with one recursive function and a clear stopping point.
Read the guide# Factorial is defined here for non-negative inputs.
func factorial(number: i32) -> i32:
if number <= 1:
return 1
return number * factorial(number - 1)
func entry(number: i32) -> i32:
return factorial(number)READABLE LOOPS
Add the odd numbers from one through the limit using a single conditional loop.
Read the guide# Add the odd numbers from 1 through the limit.
func entry(limit: i32) -> i32:
var total = 0
var number = 1
for number <= limit:
total += number
number += 2
return totalGROWABLE LISTS
Append a new score to a list, then add the scores together.
Read the guidefunc entry(latest_score: i32) -> i32:
var scores: [i32] = [10, 20]
scores.push(latest_score)
var total = 0
for score in scores:
total += score
return totalVALUES & SHARED OBJECTS
Copy a point independently while two names share one counter.
Read the guidevalue struct point:
x: i32
y: i32
struct counter:
total: i32
func entry(value: i32) -> i32:
var original = point(x = 2, y = 3)
var copied = original
copied.x += 10
var shared = counter(total = 0)
var alias = shared
alias.total += 5
return original.x + copied.x + shared.totalRESULTS & MATCHING
Return a recoverable result and handle each case explicitly.
Read the guidefunc divide(value: i32) -> result<i32, string>:
if value == 0:
return Err("division by zero")
return Ok(100 / value)
func entry(value: i32) -> i32:
var outcome = divide(value)
return match outcome:
Ok(var number): number
Err(var reason): -1func larger<t>(first: t, second: t) -> t:
if first > second:
return first
return second
func entry(score: i32) -> i32:
return larger(score, 10)value struct rectangle:
width: i32
height: i32
property (shape rectangle) area: i32:
get:
return shape.width * shape.height
func entry(width: i32) -> i32:
var panel = rectangle(width = width, height = 3)
return panel.areaFUNCTIONS & CLOSURES
Capture a starting temperature and apply one adjustment.
Read the guidefunc warmer(start: i32) -> func(i32) -> i32:
return func(change: i32) -> i32:
return start + change
func entry(temperature: i32) -> i32:
var adjust = warmer(temperature)
return adjust(3)struct sensor:
event measured: func(i32)
func (source sensor) publish(reading: i32):
source.measured.emit(reading)
struct display:
latest_reading: i32 = 0
func (screen display) update(reading: i32):
screen.latest_reading = reading
func entry(reading: i32) -> i32:
var source = sensor()
var screen = display()
source.measured += screen.update
source.publish(reading)
return screen.latest_readingSCOPED CLEANUP
Use a scope to own cleanup of a small in-memory workspace.
An in-memory teaching model of scope ownership; no external file or native-resource API is assumed.
Read the guide# An in-memory model of a workspace with scope-owned cleanup.
struct temporary_workspace:
item_count: i32
func (workspace temporary_workspace) deinit():
workspace.item_count = 0
func entry(item_count: i32) -> i32:
var processed = 0
with temporary_workspace(item_count = item_count) as workspace:
processed = workspace.item_count * 2
return processedASYNC & AWAIT
Start an estimate, prepare a packing allowance, then await the estimate.
Requires the explicit async host adapter; the ordinary synchronous CLI entry adapter does not execute this program.
Read the guideasync func travel(days: i32) -> i32:
return days * 2
async func entry(days: i32) -> i32:
var estimate = travel(days)
var packing = 2
var journey = await estimate
return journey + packingTASK GROUPS
Schedule two updates and let the task group wait for both before reading the total.
Requires the explicit async host adapter; the ordinary synchronous CLI entry adapter does not execute this program.
Read the guidestruct progress:
completed: i32 = 0
async func record_work(report: progress, amount: i32):
report.completed += amount
async func entry(amount: i32) -> i32:
var report = progress()
with tasks.group() as jobs:
var first = record_work(report, amount)
var second = record_work(report, amount + 1)
return report.completedPARALLEL WORKERS
Compute two squares independently on native workers and add their results.
Requires the explicit async host adapter; the ordinary synchronous CLI entry adapter does not execute this program.
Read the guidefunc square(number: i32) -> i32:
return number * number
async func entry(number: i32) -> i32:
var first = spawn square(number)
var second = spawn square(number + 1)
return await first + await secondMODULES & IMPORTS
Import packing arithmetic from a local module and account for the spare label.
This example also needs math/calculator.void and helpers/numbers.void, kept in those relative paths.
Read the guideuse "./math/calculator.void" as packing
use "./helpers/numbers.void" as labels
func entry(boxes: i32) -> i32:
return labels.with_spare(packing.pair(boxes))NAMED & DEFAULT ARGUMENTS
Name the distance, omit the standard rate, and spread a call across readable lines. Input five returns ten.
Read the guidefunc delivery_cost(distance: i32, rate: i32 = 2) -> i32:
return distance * rate
func entry(distance: i32) -> i32:
return delivery_cost(
distance = distance,
)UNICODE TEXT
Insert a string name and inspect one scalar. Index seven selects 界, encoded as three UTF-8 bytes. Indexes count scalars, not bytes.
Read the guidefunc entry(index: i32) -> i32:
const name = "世界"
var greeting = "Hello, {name}!"
return greeting[index].byte_length as i32APPLICATION ENTRY
Run main.void without a numeric input. Main returns process status zero and produces no standard output. This uses the application workflow, not the entry adapter.
voidc run main.void
func main() -> i32:
return 0LANGUAGE EXAMPLE
Calculate a line item through the price method required by its interface.
Read the guideinterface priced:
func price() -> i32
struct ticket:
cost: i32
func (item ticket) price() -> i32:
return item.cost
func entry(count: i32) -> i32:
var fare: priced = ticket(cost = 3)
return fare.price() * countLANGUAGE EXAMPLE
Give a delayed train a minute count and extract it by matching the variant.
Read the guideenum departure:
on_time
delayed(minutes: i32)
func entry(minutes: i32) -> i32:
var board = departure.delayed(minutes)
return match board:
departure.on_time: 0
departure.delayed(var wait): waitLANGUAGE EXAMPLE
Count the letters in a short destination name before adding the route number.
Read the guidefunc entry(route: i32) -> i32:
var stop = "林道駅"
return route + (stop.length as i32)LANGUAGE EXAMPLE
Use the platform number if one was assigned, or zero for an unassigned platform.
Read the guidestruct platform_assignment:
number: i32
func entry(number: i32) -> i32:
var platform: platform_assignment?
if number > 0:
platform = platform_assignment(number = number)
return match platform:
Ok(var assigned): assigned.number
null: 0value struct reading:
degrees: i32
struct station:
using latest: reading
func entry(degrees: i32) -> i32:
var roof = station(latest = reading(degrees = degrees))
return roof.degreesLANGUAGE EXAMPLE
Ask a base ticket reference for a group ticket’s seat count.
Read the guidestruct admission:
seats: i32
virtual func (item admission) capacity() -> i32:
return item.seats
struct group_pass extends admission:
guests: i32
override func (item group_pass) capacity() -> i32:
return super.capacity() + item.guests
func entry(guests: i32) -> i32:
var passholder = group_pass(seats = 2, guests = guests)
var booking: admission = passholder
return booking.capacity()value struct bookmark:
page: i32
func (mark bookmark) init(chapter_start: i32):
mark.page = chapter_start + 1
func entry(start: i32) -> i32:
var mark = bookmark(start)
return mark.pageLANGUAGE EXAMPLE
Retrieve the stock of a named ingredient with a recoverable lookup.
Read the guidefunc entry(lemons: i32) -> i32:
var pantry: {string: i32} = {"lemon": lemons}
if pantry.get("lemon") is Ok(var quantity):
return quantity
return 0LANGUAGE EXAMPLE
Store the size of a packet and call it to calculate a shipment.
Read the guidevalue struct packet:
size: i32
func (unit packet) call(quantity: i32) -> i32:
return unit.size * quantity
func entry(quantity: i32) -> i32:
var postcards = packet(size = 4)
return postcards(quantity)