Builtin functions

Some functions are builtin like println. Here is the complete list:

  1. // ignore
  2. fn print(s string) // prints anything on stdout
  3. fn println(s string) // prints anything and a newline on stdout
  4. fn eprint(s string) // same as print(), but uses stderr
  5. fn eprintln(s string) // same as println(), but uses stderr
  6. fn exit(code int) // terminates the program with a custom error code
  7. fn panic(s string) // prints a message and backtraces on stderr, and terminates the program with error code 1
  8. fn print_backtrace() // prints backtraces on stderr

Note: Although the print functions take a string, V accepts other printable types too. See below for details.

There is also a special built-in function called dump.

println

println is a simple yet powerful builtin function, that can print anything: strings, numbers, arrays, maps, structs.

  1. struct User {
  2. name string
  3. age int
  4. }
  5. println(1) // "1"
  6. println('hi') // "hi"
  7. println([1, 2, 3]) // "[1, 2, 3]"
  8. println(User{ name: 'Bob', age: 20 }) // "User{name:'Bob', age:20}"

See also Array methods.

Printing custom types

If you want to define a custom print value for your type, simply define a str() string method:

  1. struct Color {
  2. r int
  3. g int
  4. b int
  5. }
  6. pub fn (c Color) str() string {
  7. return '{$c.r, $c.g, $c.b}'
  8. }
  9. red := Color{
  10. r: 255
  11. g: 0
  12. b: 0
  13. }
  14. println(red)

Dumping expressions at runtime

You can dump/trace the value of any V expression using dump(expr). For example, save this code sample as factorial.v, then run it with v run factorial.v:

  1. fn factorial(n u32) u32 {
  2. if dump(n <= 1) {
  3. return dump(1)
  4. }
  5. return dump(n * factorial(n - 1))
  6. }
  7. fn main() {
  8. println(factorial(5))
  9. }

You will get:

  1. [factorial.v:2] n <= 1: false
  2. [factorial.v:2] n <= 1: false
  3. [factorial.v:2] n <= 1: false
  4. [factorial.v:2] n <= 1: false
  5. [factorial.v:2] n <= 1: true
  6. [factorial.v:3] 1: 1
  7. [factorial.v:5] n * factorial(n - 1): 2
  8. [factorial.v:5] n * factorial(n - 1): 6
  9. [factorial.v:5] n * factorial(n - 1): 24
  10. [factorial.v:5] n * factorial(n - 1): 120
  11. 120

Note that dump(expr) will trace both the source location, the expression itself, and the expression value.