V: Can't change a mutable structure field

Created on 7 Aug 2019  路  3Comments  路  Source: vlang/v

V version:
0.1.17
OS:
Win10, Debian

What did you do?

Humans are immutable, at least in my V Code
I try to change a mutable structure field with a set method()

What did you expect to see?

Foo
John is incoming
John

What did you see instead?

D:\vproj\testings\misc\json>v run main.v
pass=2 fn=set_first_name
person.v:18 person is immutable


Am i doing it wrong? I declared Person and the field first_name as mutable?
(I tried pub mut too, pub mut mut isn't in the language currently?)

main.v

module main
import untreated_data

fn main() { 

    mut person := untreated_data.Person {
        first_name: 'Foo'
        last_name: 'Bar'
        age:    25  
        job: 'Spaceship Pilot'
    }

    println(person.get_first_name())
    person.set_first_name('John')
    println(person.get_first_name())
}

person.v

module untreated_data

struct Person {
    last_name string
    age int
    job string
    mut:
        first_name string
}

pub fn (person Person) get_first_name() string {
    return person.first_name
}

pub fn (person Person) set_first_name(name string) {
    println('$name is incoming')
    // Compile Error: person.v:18 `person` is immutable
    person.first_name = ('$name')
}

Bug

Most helpful comment

I've made the error message more helpful:

make the receiver `person` mutable:
fn (person mut Person) set_first_name (...) {

Also:

cannot modify immutable field `first_name` (type `Person`)
declare the field with `mut:`

struct Person {
  mut:
    first_name string
}

All 3 comments

Try adding a mut in the parameters :
`
pub fn (person mut Person) set_first_name(name string) {
println('$name is incoming')
person.first_name = ('$name')
}
```

Oh, thank you so much :)

I've made the error message more helpful:

make the receiver `person` mutable:
fn (person mut Person) set_first_name (...) {

Also:

cannot modify immutable field `first_name` (type `Person`)
declare the field with `mut:`

struct Person {
  mut:
    first_name string
}
Was this page helpful?
0 / 5 - 0 ratings