传递给方法时,结构不通过引用传递

问题描述:

struct Data {
    public int x;
}

void change_x(Data data) {
    data.x = 123;
}

Data a = Data();
change_x(a);
print("%d", a.x); // 0

但是文档说:

当结构类型实例传递给方法时,不会进行复制.而是传递对实例的引用.
- 在 https://wiki.gnome.org/Projects/Vala/Manual/Types一个>

when a struct type instance is passed to a method, a copy is not made. Instead a reference to the instance is passed.
- in https://wiki.gnome.org/Projects/Vala/Manual/Types

怎么了?

我认为您所引用的引用文本要么已经过时,要么一开始就错了.

I think the quoted text you are refering to is either outdated or was wrong to begin with.

如果您希望通过引用传递它,则必须使用 ref(或 out)(因此得名 ref).

You have to use ref (or out) if you want it to be passed by reference (hence the name ref).

struct Data {
    public int x;
}

void change_x (ref Data data) {
    data.x = 123;
}

int main () {
    Data a = Data ();
    change_x (ref a);
    print ("%d\n", a.x);
    return 0;
}