arraysstructvlang

How do I declare and initialize const array in V lang?


What is wrong here?

struct VerbData {
    v string
    t string
}

const verbs_data = []VerbData{
        VerbData{v: "go", t: "present"},
        VerbData{v: "went", t: "past"},
        VerbData{v: "gone", t: "participle"},
}

fn main() {
    println(verbs_data)
    println(verbs_data[0].v)
}
v .\test.v
test.v:7:11: error: unexpected token `{`, expecting `:`
    5 | 
    6 | const verbs_data = []VerbData{
    7 |         VerbData{v: "go", t: "present"},
      |                 ^
    8 |         VerbData{v: "went", t: "past"},
    9 |         VerbData{v: "gone", t: "participle"},

Solution

  • Use square brackets for arrays:

    struct VerbData {
        v string
        t string
    }
    
    const verbs_data = [
        VerbData{v: "go", t: "present"},
        VerbData{v: "went", t: "past"},
        VerbData{v: "gone", t: "participle"},
    ]
    
    fn main() {
        println(verbs_data)
        println(verbs_data[0].v)
    }
    
    [VerbData{
        v: 'go'
        t: 'present'
    }, VerbData{
        v: 'went'
        t: 'past'
    }, VerbData{
        v: 'gone'
        t: 'participle'
    }]
    go