#Behaviour around functions and slices

1 messages · Page 1 of 1 (latest)

ember walrus
#

I would like to have a confirmation about my understanding of slices. Given I pass a slice of struct instances to a function like this:

fn someFunc(f: []Foo) void {}

Inside of that function I can e.g. sort the instances of Foo or change the contents of any Foo in that slice.
But! If I store "f" inside of this function to another, let's say global struct instance as a variable, I actually store a temprorary stack version of that slice (ptr) instead of the "real" one, right?

dusty seal
#

you mean something like this?

var global_f: []Foo = undefined;

fn someFunc(f: []Foo) void {
    global_f = f;
}
ember walrus
#

yes, exactly

dusty seal
#

this copies f (the .len and .ptr)

#

but not the contents it points too

ember walrus
#

hmm...so the one in global_f should be and stay correct?

dusty seal
#

global_f will have the same pointer, so it's valid as long as f is valid

#

or at least as long as f.ptr at the time the function was called is valid

ember walrus
#

ok...well, you destroyed a hope but helped very much here, thanks for that! Again a difference to how Go treats stuff.