Skip to content

casting an array to slice copies constant data instead of using the pointer #336

@andrewrk

Description

@andrewrk
test "foo" {
    const array = "hi";
    const slice: []const u8 = array;
    return bar(array, slice);
}

fn bar(args: ...) {
    const s1 = ([]const u8)(args[0]);
    const s2 = args[1];
    assert(s1.ptr == s2.ptr);
}

This behavior is problematic because you expect to be able to pass a string literal to a var args function, implicitly cast the argument to a slice, and have the pointer have the static lifetime. Instead you end up with a pointer to the stack.

I'm not quite sure how to fix this, but one idea is to automatically cast array literals to const slices for var args functions. It's kind of an arbitrary restriction though.

Maybe this is a different bug. It looks like the array is getting passed by value, and we're intending to make it an error to pass things by value with some exceptions. Maybe for var args it can implicitly cast to &const T if T is passed and T is not copyable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions