doc: add info about _ separator in literals (#5823)

pull/5828/head
Swastik Baranwal 2020-07-14 19:16:13 +05:30 committed by GitHub
parent c3ec5323f0
commit c3bdacbf04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 0 deletions

View File

@ -388,18 +388,22 @@ println(s) // "hello\nworld"
```v
a := 123
```
This will assign the value of 123 to `a`. By default `a` will have the
type `int`.
You can also use hexadecimal notation for integer literals:
```v
a := 0x7B
```
... or binary notation for integer literals:
```v
a := 0b01111011
```
... or octal notation for specifying integer literals:
```v
a := 0o173
```
@ -407,8 +411,18 @@ a := 0o173
All of these will assign the same value 123 to `a`. `a` will have the
type `int` no matter what notation you have used for the integer literal.
V also supports writing numbers with `_` as separator:
```v
num := 1_000_000 // same as 1000000
three := 0b0_11 // same as 0b11
float_num := 3_122.55 // same as 3122.55
hexa := 0xF_F // same as 255
oct := 0o17_3 // same as 0o173
```
If you want a different type of integer, you can use casting:
```v
a := i64(123)
b := byte(42)
@ -416,6 +430,7 @@ c := i16(12345)
```
Assigning floating point numbers works the same way:
```v
f := 1.0
f1 := f64(3.14)

View File

@ -144,6 +144,33 @@ fn test_oct() {
assert x9 == 0
}
fn test_num_separator() {
// int
assert 100_000_0 == 1000000
assert -2_23_4_6 == -22346
assert 230_ == 230
// bin
assert 0b0_11 == 3
assert -0b0_100 == -4
assert 0b010_ == 2
// oct
assert 0o_173 == 123
assert -0o_175 == -125
assert -0o175_ == -125
// hex
assert 0x_FF == 255
assert 0xFF_ == 255
assert 0xF_F == 255
// f32 or f64
assert 312_2.55 == 3122.55
assert 312_2.55 == 3122.55
}
fn test_int_decl() {
x1 := 0
x2 := 1333