V: .str() inside of [...] parsed incorrectly

Created on 19 Jun 2019  ·  9Comments  ·  Source: vlang/v

Input:

fn main() {
    mut m := map[string]int{}
    m['1'] = 1 
    println(m[1.str()])
}

Expected output:
1
Output:

expected `]` but got `str`
Bug

All 9 comments

but this works

fn main() {
    mut m := map[string]int{}
    m['1'] = 1
    n := 1
    println(m[n.str()])
}

This does not:

fn main() {
    mut m := map[string]int{}
    m['1'] = 1 
    n := 0 
    println(m[(n + 1).str()])
}

You just found a bug. V can't compile this program, but it should. Please create a GitHub issue.

yas, this doesn't either

fn main() {
    mut m := map[string]int{}
    m['1'] = 1 
    n := 0 
    o := 1
    println(m[(n + o).str()])
}

The reason why 1.str() does not work is because at this point 1 is a literal. literals do not know any function, they only know their value.

Once you make it into a variable however like this n := 1 . n becomes an instance of a type int, not of a literal 1. And you can call functions on types like .str().

You can call methods on types, not on literals.

It's a bit weird if literal 1 doesn't have a defined type, because it can initialize a variable i := 1. The programmer has to think of 1 as an int.

(n + o).str() should be allowed as the receiver is not mutable. n + o does have a type, it just doesn't have an address.

Interesting problem.

Literals are going to be like in Go, typeless. So that you can do a := 1 + 2.1 (a is f64, so is 1)

But I think 1.str() should be allowed.

If you do this for int, it would make sense to have it for float, no?

Something like .str(precision, rounding) so that 1.23456.str(3, true) would return “1.235” with both precision and rounding being optional.

If not, then perhaps a function str(value, precision, rounding):
Println(str(1) + “ is not equal to “ + str(1.2345, 3, true)) returning “1 is not equal to 1.235”

This has become weird now. This doesn't work:

fn main() {
    mut m := map[string]int
    m['1'] = 1 
    println(m[1.str()])
}

It returns this error:

test.v:4:19: expected type `string`, but got `f32`

But this does work:

fn main() {
    mut m := map[string]int
    m['1'] = 1 
    println(m[(1).str()])
}

Fixed, your example works now.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cjmxp picture cjmxp  ·  3Comments

taojy123 picture taojy123  ·  3Comments

PavelVozenilek picture PavelVozenilek  ·  3Comments

clpo13 picture clpo13  ·  3Comments

ArcDrake picture ArcDrake  ·  3Comments