vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.5k stars 2.15k forks source link

parser, checker: fix sorting compare fn with mut reference parameter (fix #21662) #21706

Closed yuyi98 closed 1 week ago

yuyi98 commented 1 week ago

This PR fix sorting compare fn with mut reference parameter (fix #21662).

struct Thing {
mut:
    a  int = 2
    b  int = 4
    av int
}

fn (mut t Thing) average() int {
    t.av = (t.a + t.b) / 2
    return t.av
}

struct Things {
mut:
    items []&Thing
}

fn (mut t Things) sort() {
    t.items.sort_with_compare(fn (mut a &Thing, mut b &Thing) int {
        if a.average() > b.average() {
            return 1
        } else if a.average() < b.average() {
            return -1
        }
        return 0
    })
}

fn main() {
    mut t := Things{}
    t.items << &Thing{2, 4, 0}
    t.items << &Thing{5, 7, 0}
    t.items << &Thing{1, 2, 0}
    t.sort()
    println(t)
    assert t.items.len == 3
    assert t.items[0] == &Thing{1, 2, 1}
    assert t.items[1] == &Thing{2, 4, 3}
    assert t.items[2] == &Thing{5, 7, 6}
}

PS D:\Test\v\tt1> v run .
Things{
    items: [&Thing{
    a: 1
    b: 2
    av: 1
}, &Thing{
    a: 2
    b: 4
    av: 3
}, &Thing{
    a: 5
    b: 7
    av: 6
}]
}
larpon commented 1 week ago

@yuyi98 so good to have you back mate ❤️