Examples Filter
// The latest ECMAScript standard defines seven primitive data types:

// Boolean. true and false.
let b = true;
console.log(b);

// null. A special keyword denoting a null value. (Because JavaScript is case-sensitive, null is not the same as Null, NULL, or any other variant.)
let n = null;
console.log(null);

// undefined. A top-level property whose value is not defined.
let u1 = undefined;
let u2;
console.log(u1);
console.log(u2);

// Number. An integer or floating point number. For example: 42 or 3.14159.
let n1 = 42;
let n2 = 3.14159;
console.log(n1);
console.log(n2);

// BigInt. An integer with arbitrary precision. For example: 9007199254740992n.
let big = BigInt(9007199254740991);
console.log(big);

// String. A sequence of characters that represent a text value. For example: "Howdy"
let s = "Howdy";
console.log(s);

// Symbol (new in ECMAScript 2015). A data type whose instances are unique and immutable.
let sym1 = Symbol();
let sym2 = Symbol(42);
let sym3 = Symbol('foo');
console.log(sym1, sym2, sym3);
A pointer is a programming language object that stores the memory address of another value located in computer memory.
package main

import "fmt"

func zeroval(ival int) {
    ival = 0
}

func zeroptr(iptr *int) {
    *iptr = 0
}

func main() {
    i := 1
    fmt.Println("initial:", i)

    zeroval(i)
    fmt.Println("zeroval:", i)

    zeroptr(&i)
    fmt.Println("zeroptr:", i)

    fmt.Println("pointer:", &i)
}
package main

import "fmt"

func fact(n int) int {
    if n == 0 {
        return 1
    }
    return n * fact(n-1)
}

func main() {
    fmt.Println(fact(7))
}
Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages.
package main

import (
    "fmt"
    "os"
)

func main() {

    // Immediately after getting a file object with createFile, we defer the closing of that file with closeFile.
    // This will be executed at the end of the enclosing function (main), after writeFile has finished.
    f := createFile("/tmp/defer.txt")
    defer closeFile(f)
    writeFile(f)
}

func createFile(p string) *os.File {
    fmt.Println("creating")
    f, err := os.Create(p)
    if err != nil {
        panic(err)
    }
    return f
}

func writeFile(f *os.File) {
    fmt.Println("writing")
    fmt.Fprintln(f, "data")

}

func closeFile(f *os.File) {
    fmt.Println("closing")
    err := f.Close()

    if err != nil {
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(1)
    }
}
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Go.
package main

import (
    "fmt"
    "strconv"
)

func main() {

    // With ParseFloat, this 64 tells how many bits of precision to parse.
    f, _ := strconv.ParseFloat("1.234", 64)
    fmt.Println(f)

    // For ParseInt, the 0 means infer the base from the string.
    // 64 requires that the result fit in 64 bits.
    i, _ := strconv.ParseInt("123", 0, 64)
    fmt.Println(i)

    // ParseInt will recognize hex-formatted numbers.
    d, _ := strconv.ParseInt("0x1c8", 0, 64)
    fmt.Println(d)

    u, _ := strconv.ParseUint("789", 0, 64)
    fmt.Println(u)

    // Atoi is a convenience function for basic base-10 int parsing.
    k, _ := strconv.Atoi("135")
    fmt.Println(k)

    _, e := strconv.Atoi("wat")
    fmt.Println(e)
}
module main

fn main() {
    numbers := [1, 2, 4, 5, 6, 7, 8, 9, 10]
    println(numbers)
    
    friends := ['Alex', 'Nedpals', 'Joe', 'Spytheman']
    println(friends)
    
    mut empty_numbers := []int{}
    empty_numbers << 20
    empty_numbers << 30
    println(empty_numbers)
}
Last Run  :
[1, 2, 4, 5, 6, 7, 8, 9, 10]
['Alex', 'Nedpals', 'Joe', 'Spytheman']
[20, 30]
package main

import "fmt"

type rect struct {
    width, height int
}

func (r *rect) area() int {
    return r.width * r.height
}

func (r rect) perim() int {
    return 2*r.width + 2*r.height
}

func main() {
    r := rect{width: 10, height: 5}

    fmt.Println("area: ", r.area())
    fmt.Println("perim:", r.perim())

    rp := &r
    fmt.Println("area: ", rp.area())
    fmt.Println("perim:", rp.perim())
}
package main

import (
    "fmt"
    "math"
)

type geometry interface {
    area() float64
    perim() float64
}

type rect struct {
    width, height float64
}
type circle struct {
    radius float64
}

func (r rect) area() float64 {
    return r.width * r.height
}
func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}

func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}

func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}

    measure(r)
    measure(c)
}
struct Repo {
	db DB
}

fn new_repo(db DB) Repo {
	return Repo{db: db}
}

// This is a generic function. V will generate it for every type it's used with.
fn (r Repo) find_by_id(id int) ?T {
	table_name := T.name // in this example getting the name of the type gives us the table name
	return r.db.query_one('select * from $table_name where id = ?', id)
}

db := new_db()
users_repo := new_repo(db)
posts_repo := new_repo(db)
user := users_repo.find_by_id(1)?
post := posts_repo.find_by_id(1)?
// Having built-in JSON support is nice, but V also allows you to create efficient serializers for anything:
// TODO: not implemented yet
fn decode(data string) T {
	mut result := T{}
	for field in T.fields {
		if field.typ == 'string' {
			result.$field = get_string(data, field.name)
		} else if field.typ == 'int' {
			result.$field = get_int(data, field.name)
		}
	}
	return result
}

// generates to:
fn decode_User(data string) User {
	mut result := User{}
	result.name = get_string(data, 'name')
	result.age = get_int(data, 'age')
	return result
}
You can return a value after recovering a function by using named result parameters.
package main

import "fmt"

func main() {
	fmt.Println("Returned:", MyFunc())
}

func MyFunc() (ret string) {
	defer func() {
		if r := recover(); r != nil {
			ret = fmt.Sprintf("was panic, recovered value: %v", r)
		}
	}()
	panic("test")
	return "Normal Return Value"
}
/*
Up to (Go 1.13), Go has only 25 keywords:
break     default      func    interface  select
case      defer        go      map        struct
chan      else         goto    package    switch
const     fallthrough  if      range      type
continue  for          import  return     var
*/
// Operator overloading goes against V's philosophy of simplicity and predictability.
// But since scientific and graphical applications are among V's domains, operator overloading is very important to have in order to improve readability:
// a.add(b).add(c.mul(d)) is a lot less readable than a + b + c * d.

// To improve safety and maintainability, operator overloading has several limitations:

// - It's only possible to overload +, -, *, / operators.
// - Calling other functions inside operator functions is not allowed.
// - Operator functions can't modify their arguments.
// - Both arguments must have the same type (just like with all operators in V).

struct Vec {
	x int
	y int
}

fn (a Vec) str() string {
	return '{$a.x, $a.y}'
}

fn (a Vec) + (b Vec) Vec {
	return Vec {
		a.x + b.x,
		a.y + b.y
	}
}

fn (a Vec) - (b Vec) Vec {
	return Vec {
		a.x - b.x,
		a.y - b.y
	}
}

fn main() {
	a := Vec{2, 3}
	b := Vec{4, 5}
	println(a + b) // "{6, 8}" 
	println(a - b) // "{-2, -2}" 
}
// V is a very modular language. Creating reusable modules is encouraged and is very simple.
// To create a new module, create a directory with your module's name and .v files with code:
// cd ~/code/modules
// mkdir mymodule
// vim mymodule/mymodule.v

// mymodule.v
module mymodule

// To export a function we have to use `pub`
pub fn say_hi() {
	println('hello from mymodule!')
}
// You can have as many .v files in mymodule/ as you want.
// Build it with v build module ~/code/modules/mymodule.

// That's it, you can now use it in your code:

module main

import mymodule

fn main() {
	mymodule.say_hi()
}
// Note that you have to specify the module every time you call an external function.
// This may seem verbose at first, but it makes code much more readable and easier to understand, since it's always clear which function from which module is being called. Especially in large code bases.
// Module names should be short, under 10 characters. Circular imports are not allowed.
// You can create modules anywhere.
// All modules are compiled statically into a single executable.
// If you want to write a module that will automatically call some setup/initialization code when imported (perhaps you want to call some C library functions), write a module init function inside the module:

fn init() int {
	// your setup code here ...
	return 1
}
// The init function cannot be public. It will be called automatically.
// You don't need to worry about formatting your code or style guidelines. vfmt takes care of that:
// v fmt -w file.v
// It's recommended to set up your editor, so that vfmt runs on every save.

// Always run vfmt before pushing your code.
// a one line comment
 
/* this is a longer, 
 * multi-line comment
 */
 
/* You can't, however, /* nest comments */ SyntaxError */
// The way it works is very similar to Go. It's very simple: there's no need to write documentation for your code, vdoc will generate it from the source code.
// Documentation for each function/type/const must be placed right before the declaration:

// clearall clears all bits in the array
fn clearall() {
}
// The comment must start with the name of the definition.

// An overview of the module must be placed in the first comment right after the module's name.

// To generate documentation, run v doc path/to/module (TODO this is temporarily disabled).
Last Run  :
V error: function `main` is not declared in the main module
Please add: 
fn main(){
}
... to your main program .v file, and try again.