### Install a Package with VPM Source: https://docs.vlang.io/package-management Demonstrates how to install a package from the V Package Manager (VPM). This is the standard method for adding external libraries or tools to your V project. You can also install directly from git or mercurial repositories. ```v v install [package] Example: v install ui ``` ```v v install [--once] [--git|--hg] [url] Example: v install --git https://github.com/vlang/markdown ``` ```v v install --once [package] ``` -------------------------------- ### V SQLite Module: Install and Import Source: https://docs.vlang.io/orm Explains how to install and use V's self-contained SQLite module, which wraps an SQLite amalgamation, avoiding the need for system-level installations. ```v v install sqlite import sqlite ``` -------------------------------- ### Example v.mod File Structure Source: https://docs.vlang.io/package-management An example of the `v.mod` file which describes the contents and metadata of a V package. This file is crucial for VPM to recognize and manage your package. ```v Module { name: 'mypackage' description: 'My nice package.' version: '0.0.1' license: 'MIT' dependencies: [] } ``` -------------------------------- ### V Test File Example (Internal Test) Source: https://docs.vlang.io/testing Provides an example of an internal test file in V, named `hello_test.v`. This file tests the `hello` function defined in `hello.v` within the same module (`main`). Internal tests can call private functions of the module they belong to. ```v // hello.v module main fn hello() string { return 'Hello world' } fn main() { println(hello()) } ``` ```v // hello_test.v module main fn test_hello() { assert hello() == 'Hello world' } ``` -------------------------------- ### V Cross-platform Shell Script Example Source: https://docs.vlang.io/other-v-features An example of a V shell script (.vsh) demonstrating cross-platform capabilities. It includes functions for directory manipulation, file operations, and executing shell commands, suitable for build or deployment tasks. ```v #!/usr/bin/env -S v // Note: The shebang line above, associates the .vsh file to V on Unix-like systems, // so it can be run just by specifying the path to the .vsh file, once it's made // executable, using `chmod +x deploy.vsh`, i.e. after that chmod command, you can // run the .vsh script, by just typing its name/path like this: `./deploy.vsh` // print command then execute it fn sh(cmd string) { println('❯ ${cmd}') print(execute_or_exit(cmd).output) } // Remove if build/ exits, ignore any errors if it doesn't rmdir_all('build') or {} // Create build/, never fails as build/ does not exist mkdir('build')! // Move *.v files to build/ result := execute('mv *.v build/') if result.exit_code != 0 { println(result.output) } sh('ls') // Similar to: // files := ls('.')! // mut count := 0 // if files.len > 0 { // for file in files { // if file.ends_with('.v') { // mv(file, 'build/') or { // println('err: ${err}') // return // } // } // count++ // } // } // if count == 0 { // println('No files') // } ``` -------------------------------- ### List Installed Packages with VPM Source: https://docs.vlang.io/package-management Provides the command to list all packages currently installed in your V environment. This is useful for keeping track of your project's dependencies. ```v v list Example: > v list Installed packages: markdown ui ``` -------------------------------- ### V SQLite Troubleshooting: Install Third-Party Source: https://docs.vlang.io/orm Provides instructions for resolving SQLite compilation errors on Windows by installing the necessary third-party components. ```v v vlib/db/sqlite/install_thirdparty_sqlite.vsh ``` -------------------------------- ### Install MinGW-w64 for Windows Cross-Compilation on Arch Linux Source: https://docs.vlang.io/cross-compilation Installs the GNU C compiler for MinGW-w64 on Arch Linux-based distributions, a necessary step for cross-compiling Windows binaries. ```bash sudo pacman -S mingw-w64-gcc ``` -------------------------------- ### Integrate with SQLite C API in V Source: https://docs.vlang.io/v-and-c Provides an example of integrating with the SQLite C API in V. It includes redeclarations for SQLite structures and functions, along with flag directives for linking. ```v #flag freebsd -I/usr/local/include -L/usr/local/lib #flag -lsqlite3 #include "sqlite3.h" // See also the example from https://www.sqlite.org/quickstart.html pub struct C.sqlite3 { } pub struct C.sqlite3_stmt { } type FnSqlite3Callback = fn (voidptr, int, &&char, &&char) int fn C.sqlite3_open(&char, &&C.sqlite3) int fn C.sqlite3_close(&C.sqlite3) int fn C.sqlite3_column_int(stmt &C.sqlite3_stmt, n int) int // ... you can also just define the type of parameter and leave out the C. prefix ``` -------------------------------- ### Heap Allocation for Vlang Structs Source: https://docs.vlang.io/structs Explains how to allocate a struct on the heap using the '&' prefix to get a reference. It demonstrates initialization and accessing fields through the reference, noting that references behave similarly to pointers. ```v struct Point { x int y int } p := &Point{10, 10} // References have the same syntax for accessing fields println(p.x) ``` -------------------------------- ### Profile-Guided Optimization (PGO) Setup with Clang Source: https://docs.vlang.io/performance-tuning This bash script demonstrates setting up Profile-Guided Optimization (PGO) for a Vlang CLI program using Clang. It involves an initial build with PGO instrumentation, followed by running the instrumented binary to generate profile data. ```bash #!/usr/bin/env bash # Get the full path to the current directory CUR_DIR=$(pwd) # Remove existing PGO data rm -f *.profraw rm -f default.profdata # Initial build with PGO instrumentation v -cc clang -prod -cflags -fprofile-generate -o pgo_gen . ``` -------------------------------- ### Install MinGW-w64 for Windows Cross-Compilation on Ubuntu/Debian Source: https://docs.vlang.io/cross-compilation Installs the GNU C compiler for MinGW-w64, which is required for cross-compiling Windows binaries (Win64) on Ubuntu or Debian-based Linux distributions. ```bash sudo apt install gcc-mingw-w64-x86-64 ``` -------------------------------- ### Vlang Atomic Compare-and-Exchange Example Source: https://docs.vlang.io/atomics This example showcases the use of `atomic_compare_exchange_strong_u32` in Vlang for thread-safe updates to a global variable. It includes a spawned thread `change()` and the `main()` function competing to update the `atom` variable, demonstrating race condition handling and predicting the final state. ```v // see section "Global Variables" below __global ( atom u32 // ordinary variable but used as atomic ) fn change() int { mut races_won_by_change := 0 for { mut cmp := u32(17) // addressable value to compare with and to store the found value // atomic version of `if atom == 17 { atom = 23 races_won_by_change++ } else { cmp = atom }` if C.atomic_compare_exchange_strong_u32(&atom, &cmp, 23) { races_won_by_change++ } else { if cmp == 31 { break } cmp = 17 // re-assign because overwritten with value of atom } } return races_won_by_change } fn main() { C.atomic_store_u32(&atom, 17) t := spawn change() mut races_won_by_main := 0 mut cmp17 := u32(17) mut cmp23 := u32(23) for i in 0 .. num_iterations { // atomic version of `if atom == 17 { atom = 23 races_won_by_main++ }` if C.atomic_compare_exchange_strong_u32(&atom, &cmp17, 23) { races_won_by_main++ } else { cmp17 = 17 } desir := if i == num_iterations - 1 { u32(31) } else { u32(17) } // atomic version of `for atom != 23 {} atom = desir` for !C.atomic_compare_exchange_weak_u32(&atom, &cmp23, desir) { cmp23 = 23 } } races_won_by_change := t.wait() atom_new := C.atomic_load_u32(&atom) println('atom: ${atom_new}, #exchanges: ${races_won_by_main + races_won_by_change}') // prints `atom: 31, #exchanges: 10000000` println('races won by\n- `main()`: ${races_won_by_main}\n- `change()`: ${races_won_by_change}') } const num_iterations = 10000000 ``` -------------------------------- ### Vlang Multidimensional Array Initialization Source: https://docs.vlang.io/v-types Illustrates the creation and modification of multidimensional arrays in Vlang. This includes examples for 2D and 3D arrays, showing how to initialize their dimensions and assign values to specific elements. ```v mut a := [][]int{len: 2, init: []int{len: 3}} a[0][1] = 2 println(a) // [[0, 2, 0], [0, 0, 0]] ``` ```v mut a := [][][]int{len: 2, init: [][]int{len: 3, init: []int{len: 2}}} a[0][1][1] = 2 println(a) // [[[0, 0], [0, 2], [0, 0]], [[0, 0], [0, 0], [0, 0]]] ``` -------------------------------- ### Vlang Structs with Keyword Reuse Source: https://docs.vlang.io/structs Shows how struct fields can reuse reserved keywords in Vlang, using 'type' as an example for a string field. It demonstrates initialization and accessing such fields. ```v struct Employee { type string name string } employee := Employee{ type: 'FTE' name: 'John Doe' } println(employee.type) ``` -------------------------------- ### Update an Installed Package with VPM Source: https://docs.vlang.io/package-management Illustrates how to update a specific installed package or all outdated packages using VPM. Keeping packages updated ensures you have the latest features and bug fixes. ```v v update [package] Example: v update ui ``` ```v v update ``` -------------------------------- ### Vlang Module Initialization Function Source: https://docs.vlang.io/modules This Vlang snippet shows the structure of an 'init' function within a module. This function is automatically called once when the module is imported, useful for setup. ```v fn init() { // your setup code here ... } ``` -------------------------------- ### Access CLI arguments in V program Source: https://docs.vlang.io/running-a-project-folder-with-several-files Example V code demonstrating how to access command-line arguments passed to the program. The `os.args` array contains the program name and any arguments provided during execution. ```v import os println(os.args) ``` -------------------------------- ### V Package Manager Commands Source: https://docs.vlang.io/package-management This section outlines the primary commands for interacting with the V package manager (VPM). These commands allow users to manage packages installed from the V Package Manager (VPM). ```v v [package_command] [param] where a package command can be one of: install Install a package from VPM. remove Remove a package that was installed from VPM. search Search for a package from VPM. update Update an installed package from VPM. upgrade Upgrade all the outdated packages. list List all installed packages. outdated Show installed packages that need updates. ``` -------------------------------- ### Check for Outdated Packages with VPM Source: https://docs.vlang.io/package-management Shows the command to identify installed packages that have available updates. This helps in maintaining your projects with the latest versions. ```v v outdated Example: > v outdated Package are up to date. ``` -------------------------------- ### Redeclare and Call `dprintf` from stdio in V Source: https://docs.vlang.io/v-and-c An example of redeclaring the C standard library function `dprintf` in V and then calling it. It demonstrates handling variadic arguments using `...voidptr`. ```v #include // int dprintf(int fd, const char *format, ...) fn C.dprintf(fd int, const_format &char, ...voidptr) int value := 12345 x := C.dprintf(0, c'Hello world, value: %d\n', value) dump(x) ``` -------------------------------- ### Vlang Function Tracing Execution Example Source: https://docs.vlang.io/trace This command shows how to compile and run a Vlang program with the trace debugging flag enabled. The output demonstrates the effect of the before and after call hooks added to the `anon` function. ```Shell $ v -d trace run example.v > before anon call > after anon call ``` -------------------------------- ### Vlang Buffered Channel Usage Source: https://docs.vlang.io/concurrency Shows how to use buffered channels in Vlang, allowing multiple items to be pushed without blocking as long as the buffer is not full. This example demonstrates sending and receiving from a buffered string channel. ```v ch := chan string{cap: 2} ch <- 'hello' ch <- 'world' // ch <- '!' // This would block because the buffer is full println(<-ch) // "hello" println(<-ch) // "world" ``` -------------------------------- ### Vlang Struct Initialization with Reference Fields Source: https://docs.vlang.io/structs-with-reference-fields Demonstrates the declaration and initialization of Vlang structs containing reference fields. It shows how to initialize fields with nil pointers and with references to other struct instances. The example also illustrates the automatic initialization of fields when a default value is provided. ```vlang struct Node { a &Node b &Node = unsafe { nil } // Auto-initialized to nil, use with caution! } // Reference fields must be initialized unless an initial value is declared. // Nil is OK but use with caution, it's a nil pointer. foo := Node{ a: unsafe { nil } } bar := Node{ a: &foo } baz := Node{ a: unsafe { nil } b: unsafe { nil } } qux := Node{ a: &foo b: &bar } println(baz) println(qux) ``` -------------------------------- ### Translate C file to V code Source: https://docs.vlang.io/v-and-c Translates a given C file into a human-readable V file using Clang's AST. Requires Clang to be installed. Outputs a .v file with equivalent functionality. ```bash v translate test.c ``` ```v fn main() { for i := 0; i < 10; i++ { println('hello world') } } ``` -------------------------------- ### Printing Build Time with @BUILD_TIMESTAMP in V Source: https://docs.vlang.io/conditional-compilation This example shows how to print the compilation time of a V program using the `@BUILD_TIMESTAMP` pseudo-variable, converting it to a human-readable format. It requires importing the `time` module. ```V import time println('This program, was compiled at ${time.unix(@BUILD_TIMESTAMP.i64()).format_ss_milli()} .') ``` -------------------------------- ### V Structs and Interfaces Example Source: https://docs.vlang.io/type-declarations Demonstrates defining structs (Dog, Cat) and an interface (Speaker) in V. It shows how to create instances of structs, add them to a slice of the interface type, and iterate to call methods defined in the interface. This highlights V's support for polymorphism similar to TypeScript. ```v struct Dog { breed string } fn (d Dog) speak() string { return 'woof' } struct Cat { breed string } fn (c Cat) speak() string { return 'meow' } interface Speaker { breed string speak() string } fn main() { dog := Dog{'Leonberger'} cat := Cat{'Siamese'} mut arr := []Speaker{} arr << dog arr << cat for item in arr { println('a ${item.breed} says: ${item.speak()}') } } ``` -------------------------------- ### V ORM: Insert Customer Records Source: https://docs.vlang.io/orm Demonstrates inserting new customer records into the 'Customer' table using V's ORM. It includes examples for customers with and without a country specified. ```v new_customer := Customer{ name: 'Bob' country: 'uk' nr_orders: 10 } sql db { insert new_customer into Customer }! us_customer := Customer{ name: 'Martin' country: 'us' nr_orders: 5 } sql db { insert us_customer into Customer }! none_country_customer := Customer{ name: 'Dennis' country: none nr_orders: 2 } sql db { insert none_country_customer into Customer }! ``` -------------------------------- ### Vlang: Optimize Array Appending with Pre-set Capacity Source: https://docs.vlang.io/v-types Shows how setting the `cap` during initialization can improve performance by avoiding reallocations when appending elements. This example appends 1000 elements to an array with a capacity of 1000. ```Vlang mut numbers := []int{cap: 1000} println(numbers.len) // 0 // Now appending elements won't reallocate for i in 0 .. 1000 { numbers << i } ``` -------------------------------- ### V Built-in Println Function Examples Source: https://docs.vlang.io/builtin-functions Demonstrates the versatility of the `println` function, showing its ability to print various data types including integers, strings, arrays, and structs. Custom types can be printed by implementing the `str()` method. ```v struct User { name string age int } println(1) println('hi') println([1, 2, 3]) println(User{ name: 'Bob', age: 20 }) ``` -------------------------------- ### vdoc: Documenting a simple function Source: https://docs.vlang.io/writing-documentation This snippet demonstrates how to document a function in vlang using a docstring. The docstring should immediately precede the function declaration and start with the function's name. vdoc automatically generates documentation from these comments. ```vlang /* clearall clears all bits in the array */ fn clearall() { } ``` -------------------------------- ### Vlang Package Management with #pkgconfig Source: https://docs.vlang.io/v-and-c This snippet illustrates the use of the `#pkgconfig` directive in Vlang to manage dependencies via pkg-config. It shows how to include compiler and linker flags automatically by referencing a pkg-config module like 'r_core'. The example also includes conditional compilation based on the availability of a pkg-config module. ```v #pkgconfig r_core #pkgconfig --cflags --libs r_core $if $pkgconfig('mysqlclient') { #pkgconfig mysqlclient } $else $if $pkgconfig('mariadb') { #pkgconfig mariadb } ``` -------------------------------- ### Programmatic Test Execution in Vlang Source: https://docs.vlang.io/testing Example of how a Vlang test file can execute another test file programmatically. It utilizes the `@VEXE` constant for the V compiler path and asserts the expected output and exit code. ```v import os fn test_subtest() { res := os.execute('${os.quoted_path(@VEXE)} other_test.v') assert res.exit_code == 1 assert res.output.contains('other_test.v does not exist') } ``` -------------------------------- ### Vlang Channel Select with Timeout and Else Source: https://docs.vlang.io/concurrency Demonstrates the `select` statement in Vlang for monitoring multiple channels. It shows how to handle data received from channels, send data to channels, and includes optional timeout and else branches for non-blocking operations. This example uses channels of f64 and illustrates spawning threads to interact with these channels. ```Vlang import time fn main() { ch := chan f64{} ch2 := chan f64{} ch3 := chan f64{} mut b := 0.0 c := 1.0 // ... setup spawn threads that will send on ch/ch2 spawn fn (the_channel chan f64) { time.sleep(5 * time.millisecond) the_channel <- 1.0 }(ch) spawn fn (the_channel chan f64) { time.sleep(1 * time.millisecond) the_channel <- 1.0 }(ch2) spawn fn (the_channel chan f64) { _ := <-the_channel }(ch3) select { a := <-ch { // do something with `a` eprintln('> a: ${a}') } b = <-ch2 { // do something with predeclared variable `b` eprintln('> b: ${b}') } ch3 <- c { // do something if `c` was sent time.sleep(5 * time.millisecond) eprintln('> c: ${c} was send on channel ch3') } 500 * time.millisecond { // do something if no channel has become ready within 0.5s eprintln('> more than 0.5s passed without a channel being ready') } } eprintln('> done') } ``` -------------------------------- ### Vlang Nested Map Initialization and Access Source: https://docs.vlang.io/v-types Shows how to create and manipulate nested maps in V. This example demonstrates initializing a map where values are themselves maps, allowing for multi-level data structuring. It includes adding entries to nested maps. ```v mut m := map[string]map[string]int{} m['greet'] = { 'Hello': 1 } m['place'] = { 'world': 2 } // m['code']['orange'] = 123 // This line would cause a compile-time error if 'code' is not initialized print(m) ``` -------------------------------- ### V Interface Implementation Example Source: https://docs.vlang.io/type-declarations Illustrates the implementation of interfaces in V, differentiating between interfaces with mutable and immutable methods. It shows how a struct must match the method signatures, including mutability, to implement an interface. Compile-time errors are demonstrated when a struct fails to implement a required mutable method. ```v interface Foo { write(string) string } interface Bar { mut: write(string) string } struct MyStruct {} // MyStruct implements the interface Foo, but *not* interface Bar fn (s MyStruct) write(a string) string { return a } fn main() { s1 := MyStruct{} fn1(s1) // fn2(s1) -> compile error, since MyStruct does not implement Bar } fn fn1(s Foo) { println(s.write('Foo')) } // fn fn2(s Bar) { // does not match // println(s.write('Foo')) // } ``` -------------------------------- ### V Assert Statement Example Source: https://docs.vlang.io/testing Demonstrates the basic usage of the assert statement in V. Asserts check if an expression evaluates to true. If it fails, the program typically aborts and prints diagnostic information. Asserts are removed when compiling with the -prod flag. ```v fn foo(mut v []int) { v[0] = 1 } mut v := [20] foo(mut v) assert v[0] < 4 ``` -------------------------------- ### Initialize Git Repository for Package Source: https://docs.vlang.io/package-management Shows the commands to initialize a git repository and commit the initial files for a V package. This is a prerequisite for publishing your package to remote repositories. ```bash git init git add . git commit -m "INIT" ``` -------------------------------- ### Lambda Expressions as Callbacks in V Source: https://docs.vlang.io/functions-2 Demonstrates using a lambda expression as a callback function in V. The example defines a function `f` that accepts a callback `cb` and executes it with a specific argument, showcasing the flexibility of lambdas for event handling or asynchronous operations. ```v // Lambda function can be used as callback fn f(cb fn (a int) int) int { return cb(10) } println(f(|x| x + 4)) // prints 14 ``` -------------------------------- ### Vlang Hello World with Explicit Main Function Source: https://docs.vlang.io/hello-world This Vlang 'Hello World' program explicitly defines the `main` function, which serves as the entry point for execution. It uses `println` to output 'hello world' to the console. This structure is common in larger V projects. ```v fn main() { println('hello world') } ``` -------------------------------- ### Vlang Basic Hello World Program Source: https://docs.vlang.io/hello-world This is the most basic 'Hello World' program in Vlang. It demonstrates the use of the `println` function for standard output. This version omits the explicit `fn main()` declaration, relying on V's implicit main function behavior. ```v println('hello world') ``` -------------------------------- ### Create a New V Package Source: https://docs.vlang.io/package-management Demonstrates the initial steps to create a new V package, including using the `v new` command and setting up the necessary `v.mod` file. This process is essential for publishing your own V packages. ```v v new mypackage Input your project description: My nice package. Input your project version: (0.0.0) 0.0.1 Input your project license: (MIT) Initialising ... Complete! ``` -------------------------------- ### Define and Initialize a Basic Vlang Struct Source: https://docs.vlang.io/structs Demonstrates how to define a struct named 'Point' with integer fields 'x' and 'y', and how to initialize it using both explicit field assignment and a positional literal syntax. Also shows accessing struct fields. ```v struct Point { x int y int } mut p := Point{ x: 10 y: 20 } println(p.x) // Struct fields are accessed using a dot // Alternative literal syntax p = Point{10, 20} assert p.x == 10 ``` -------------------------------- ### V ORM: Create Customer Table Source: https://docs.vlang.io/orm This code snippet shows how to create a table in the database based on the 'Customer' struct definition using V's ORM syntax. ```v sql db { create table Customer }! ``` -------------------------------- ### Vlang Map Initialization with Short Syntax Source: https://docs.vlang.io/v-types Demonstrates a concise syntax for initializing maps in V. This method allows for direct declaration and population of map entries, making map creation more readable for predefined data. ```v numbers := { 'one': 1 'two': 2 } println(numbers) ``` -------------------------------- ### Remove a Package with VPM Source: https://docs.vlang.io/package-management Shows the command to remove a package that has been previously installed using VPM. This helps in managing project dependencies and freeing up space. ```v v remove [package] Example: v remove ui ``` -------------------------------- ### Create a New Vlang Module Directory Source: https://docs.vlang.io/modules This snippet demonstrates how to create a new directory for a Vlang module and a sample file within it. It sets up the basic structure for a reusable module. ```bash cd ~/code/modules mkdir mymodule vim mymodule/myfile.v ``` -------------------------------- ### Run V project folder with CLI arguments Source: https://docs.vlang.io/running-a-project-folder-with-several-files This command compiles all .v files in the current directory into a single executable and then runs it. Any arguments following the '.' are passed to the program as CLI parameters. This is useful for projects with multiple helper files not yet structured into modules. ```shell v run . --yourparam some_other_stuff ``` -------------------------------- ### Cross Compile V Project for Windows Source: https://docs.vlang.io/cross-compilation Command to cross-compile a V project targeting the Windows operating system. Ensure necessary toolchains like MinGW-w64 are installed if cross-compiling from Linux. ```bash v -os windows . ``` -------------------------------- ### V String Immutability Example Source: https://docs.vlang.io/v-types Demonstrates that V strings are immutable and cannot be modified directly after creation. Attempting to assign a new value to a string index will result in a compilation error. ```v mut s := 'hello 🌎' // s[0] = `H` // not allowed // > error: cannot assign to `s[i]` since V strings are immutable ``` -------------------------------- ### Vlang SQLite C API Bindings Source: https://docs.vlang.io/v-and-c This snippet demonstrates Vlang's C API bindings for SQLite. It includes functions for preparing SQL statements, executing them, stepping through results, finalizing statements, freeing memory, and executing SQL commands with callbacks. It also shows a sample callback function and the main function to open a database, execute queries, and close the connection. ```v fn C.sqlite3_prepare_v2(&C.sqlite3, &char, int, &&C.sqlite3_stmt, &&char) int fn C.sqlite3_step(&C.sqlite3_stmt) fn C.sqlite3_finalize(&C.sqlite3_stmt) fn C.sqlite3_exec(db &C.sqlite3, sql &char, cb FnSqlite3Callback, cb_arg voidptr, emsg &&char) int fn C.sqlite3_free(voidptr) fn my_callback(arg voidptr, howmany int, cvalues &&char, cnames &&char) int { unsafe { for i in 0 .. howmany { print('| ${cstring_to_vstring(cnames[i])}: ${cstring_to_vstring(cvalues[i])}:20 ') } } println('|') return 0 } fn main() { db := &C.sqlite3(unsafe { nil }) C.sqlite3_open(c'users.db', &db) query := 'select count(*) from users' stmt := &C.sqlite3_stmt(unsafe { nil }) C.sqlite3_prepare_v2(db, &char(query.str), -1, &stmt, 0) C.sqlite3_step(stmt) nr_users := C.sqlite3_column_int(stmt, 0) C.sqlite3_finalize(stmt) println('There are ${nr_users} users in the database.') error_msg := &char(unsafe { nil }) query_all_users := 'select * from users' rc := C.sqlite3_exec(db, &char(query_all_users.str), my_callback, voidptr(7), &error_msg) if rc != C.SQLITE_OK { eprintln(unsafe { cstring_to_vstring(error_msg) }) C.sqlite3_free(error_msg) } C.sqlite3_close(db) } ``` -------------------------------- ### Vlang Array Manipulation Methods Source: https://docs.vlang.io/v-types Provides examples of common Vlang array manipulation methods such as repeating, inserting, prepending, trimming, clearing, deleting elements, and accessing first/last elements. ```v a := [1, 2] a_repeated := a.repeat(3) println(a_repeated) // [1, 2, 1, 2, 1, 2] ``` ```v a := [1, 2, 3] a.insert(1, 99) println(a) // [1, 99, 2, 3] ``` ```v a := [1, 2, 3] a.insert(1, [4, 5]) println(a) // [1, 4, 5, 2, 3] ``` ```v a := [1, 2, 3] a.prepend(0) println(a) // [0, 1, 2, 3] ``` ```v a := [1, 2, 3] other_arr := [4, 5] a.prepend(other_arr) println(a) // [4, 5, 1, 2, 3] ``` ```v a := [1, 2, 3, 4, 5] a.trim(3) println(a) // [1, 2, 3] ``` ```v a := [1, 2, 3] a.clear() println(a) // [] ``` ```v a := [1, 2, 3, 4, 5] a.delete_many(1, 2) println(a) // [1, 4, 5] ``` ```v a := [1, 2, 3] a.delete(1) println(a) // [1, 3] ``` ```v a := [1, 2, 3] a.delete_last() println(a) // [1, 2] ``` ```v a := [1, 2, 3] println(a.first()) // 1 ``` ```v a := [1, 2, 3] println(a.last()) // 3 ``` ```v a := [1, 2, 3] popped_value := a.pop() println(popped_value) // 3 println(a) // [1, 2] ``` ```v a := [1, 2, 3] reversed_a := a.reverse() println(reversed_a) // [3, 2, 1] println(a) // [1, 2, 3] ``` ```v a := [1, 2, 3] a.reverse_in_place() println(a) // [3, 2, 1] ``` ```v words := ['hello', ' ', 'world'] joined_string := words.join('') println(joined_string) // hello world ``` -------------------------------- ### Import and Use a Vlang Module Source: https://docs.vlang.io/modules This Vlang code demonstrates how to import the 'mymodule' and use its exported functions 'say_hi' and 'say_hi_and_bye' within the main function. ```v import mymodule fn main() { mymodule.say_hi() mymodule.say_hi_and_bye() } ``` -------------------------------- ### Full Module Import in V Source: https://docs.vlang.io/module-imports Demonstrates importing the entire 'os' module to access its functions like 'input' and 'println'. This approach requires prefixing external functions with the module name, enhancing code readability. It's suitable for projects where clarity on function origins is paramount. ```V import os fn main() { // read text from stdin name := os.input('Enter your name: ') println('Hello, ${name}!') } ``` -------------------------------- ### Vlang Goto Statement Example Source: https://docs.vlang.io/statements-%26-expressions Illustrates the usage of the 'goto' statement in Vlang for unconditional jumps to a label within the same function. This feature requires an 'unsafe' block due to potential memory-safety risks. ```vlang if x { // ... if y { unsafe { goto my_label } } // ... } my_label: ``` -------------------------------- ### Vlang If Unwrapping with Struct Assignment Source: https://docs.vlang.io/statements-%26-expressions Shows 'if unwrapping' in Vlang used for assigning a value derived from a conditional check to a new variable. This example accesses a struct field within an array. ```v struct User { name string } arr := [User{'John'}] // if unwrapping with assignment of a variable u_name := if v := arr[0] { v.name } else { 'Unnamed' } println(u_name) // John ``` -------------------------------- ### Embedding v.mod Info with @VMOD_FILE in V Source: https://docs.vlang.io/conditional-compilation This example shows how to embed and display the name, version, and description from a `v.mod` file into an executable using the `@VMOD_FILE` pseudo-variable. It requires importing the `v.vmod` module. ```V import v.vmod vm := vmod.decode( @VMOD_FILE )! eprintln('${vm.name} ${vm.version}\n${vm.description}') ``` -------------------------------- ### V ORM: Define Customer Model and Connect to SQLite Source: https://docs.vlang.io/orm This snippet demonstrates how to define a 'Customer' struct with ORM annotations for table naming and field properties. It also shows how to connect to an SQLite database. ```v import db.sqlite @[table: 'customers'] struct Customer { id int @[primary; serial] // a field named `id` of integer type must be the first field name string nr_orders int country ?string } db := sqlite.connect('customers.db')! ``` -------------------------------- ### Required Fields in Vlang Structs Source: https://docs.vlang.io/structs Explains how to mark struct fields with the `@[required]` attribute to ensure they are initialized during struct instantiation. It provides an example that would fail to compile if a required field is not initialized. ```v struct Foo { n int @[required] } // This example will not compile, since the field `n` isn't explicitly initialized: // _ = Foo{} ``` -------------------------------- ### Vlang Array Mapping with Anonymous Functions Source: https://docs.vlang.io/v-types Illustrates how to transform elements of an array using the `.map()` method in Vlang. Examples include transforming strings to uppercase using both `it` and explicit anonymous functions. ```v words := ['hello', 'world'] upper := words.map(it.to_upper()) println(upper) // ['HELLO', 'WORLD'] ``` ```v words := ['hello', 'world'] upper_fn := words.map(fn (w string) string { return w.to_upper() }) println(upper_fn) // ['HELLO', 'WORLD'] ``` -------------------------------- ### V Module Configuration for C Code Source: https://docs.vlang.io/v-and-c This snippet shows the necessary additions to a v.mod file to include C code. It specifies the C code's location and flags for compilation and linking. @VMODROOT is a placeholder replaced by V with the nearest parent folder containing a v.mod file. ```v #flag -I @VMODROOT/c #flag @VMODROOT/c/implementation.o #include "header.h" ``` -------------------------------- ### C Struct Redeclaration in V Source: https://docs.vlang.io/v-and-c Explains how to redeclare C structures in V to access their members. This example shows how to declare a complex C struct with a union, even if sub-data-structures cannot be directly represented in V. ```v pub struct C.SomeCStruct { implTraits u8 memPoolData u16 // These members are part of sub data structures that can't currently be represented in V. // Declaring them directly like this is sufficient for access. // union { // struct { data voidptr size usize // } view C.DataView // } } ``` -------------------------------- ### Vlang Basic Function Declaration and Execution Source: https://docs.vlang.io/functions Demonstrates the declaration and execution of basic functions in Vlang. It shows how to define functions like `add` and `sub` and call them from the `main` function. Vlang supports function hoisting, allowing functions to be called before their declaration. ```v fn main() { println(add(77, 33)) println(sub(100, 50)) } fn add(x int, y int) int { return x + y } fn sub(x int, y int) int { return x - y } ``` -------------------------------- ### C String to V String Conversion Source: https://docs.vlang.io/v-and-c Demonstrates how to convert C zero-terminated strings (char*) to V strings. It includes methods for conversion when the length is known and a utility function for creating a copy of the C string if necessary. ```v unsafe { &char(cstring).vstring() } unsafe { &char(cstring).vstring_with_len(len) } cstring_to_vstring(cstring) ``` -------------------------------- ### Vlang Enum with Methods Source: https://docs.vlang.io/type-declarations Demonstrates defining methods for enums in Vlang. The `Cycle` enum has a `next()` method that cycles through its values. The example iterates and prints the next cycle value. ```v enum Cycle { one two three } fn (c Cycle) next() Cycle { match c { .one { return .two } .two { return .three } .three { return .one } } } mut c := Cycle.one for _ in 0 .. 10 { println(c) c = c.next() } ``` -------------------------------- ### Vlang Enum with Keyword Re-use Source: https://docs.vlang.io/type-declarations Illustrates that enum fields can reuse reserved keywords in Vlang. The example shows an enum `Color` using `none`, `red`, `green`, and `blue`. ```v enum Color { none red green blue } color := Color.none println(color) ``` -------------------------------- ### Include C headers after V built-ins Source: https://docs.vlang.io/v-and-c Uses the #postinclude directive to include a C header file after V has included its built-in libraries. This is helpful for integrating with C libraries that require specific setup or callbacks. ```c #include "include.h" ``` -------------------------------- ### Vlang Embedded Interface Example Source: https://docs.vlang.io/type-declarations Illustrates interface embedding in Vlang, where one interface can include all methods and fields of another. `ReaderWriter` embeds `Reader` and `Writer`, effectively combining their definitions. ```v pub interface Reader { mut: read(mut buf []u8) ?int } pub interface Writer { mut: write(buf []u8) ?int } // ReaderWriter embeds both Reader and Writer. // The effect is the same as copy/paste all of the // Reader and all of the Writer methods/fields into // ReaderWriter. pub interface ReaderWriter { Reader Writer } ``` -------------------------------- ### Generate V wrapper for C library Source: https://docs.vlang.io/v-and-c Generates a V module wrapper for a C library source directory. This simplifies C interop by creating V bindings for the library's functions and structures. ```bash v translate wrapper c_code/libsodium/src/libsodium ``` -------------------------------- ### V Static Variable Example Source: https://docs.vlang.io/static-variables Demonstrates the usage of static variables within an unsafe function in V. The static variable 'x' is initialized once and its value persists across multiple calls to the counter function, showcasing statefulness. ```v @[unsafe] fn counter() int { mut static x := 42 // Note: x is initialised to 42, just _once_. x++ return x } fn f() int { return unsafe { counter() } } println(f()) // prints 43 println(f()) // prints 44 println(f()) // prints 45 ```