New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Const and slices, wrong const checking #1565

Closed
UniqueID1 opened this Issue Sep 20, 2018 · 2 comments

Comments

Projects
None yet
2 participants
@UniqueID1

UniqueID1 commented Sep 20, 2018

The first issue is that this compiles:

const buffer: [1]u8 = []u8{8};
const sliceA: []u8 = &buffer;
var sliceB: []u8 = &buffer;

Buffer is constant data, the slices are to mutable data.

Here comes the weird part, I can not do this:
sliceA[0] = 0; // error: cannot assign to constant
sliceB[0] = 0; // works fine
Both should work, given their type.

However, if "const buffer" is changed to "var buffer" then both now work despite sliceA's type never changing:
sliceA[0] = 0; // works
sliceB[0] = 0; // works

@andrewrk andrewrk added this to the 0.3.0 milestone Sep 20, 2018

@andrewrk andrewrk added the bug label Sep 20, 2018

@UniqueID1

This comment has been minimized.

UniqueID1 commented Sep 20, 2018

More (but different):

const array = []u8{1,2,3,4,5,6,7,8};

const ptrA: [*]const u8 = @ptrCast([*]const u8, &array);
const sliceA: []const u8 = ptrA[0..2]; // error: out of bounds slice

const ptrB: [*]const u8 = &array;
const sliceB: []const u8 = ptrB[0..2]; // works, what differs is @ptrCast is gone

Change "const array" to "var array" and it all compiles. You can also change "const ptrA" to "var ptrA" and it also all compiles. Note that the error here is "error: out of bounds slice", it's not an error about const.

I don't know if this is a different bug or not.

andrewrk added a commit that referenced this issue Sep 20, 2018

@andrewrk

This comment has been minimized.

Member

andrewrk commented Sep 20, 2018

First example is fixed. const sliceA: []u8 = &buffer; is a compile error for casting a const array to a mutable slice. Now looking at the second test case.

@andrewrk andrewrk closed this in 44f2ee1 Sep 21, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment