Skip to content
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

Example is incorrect #19249

Closed
swork1 opened this issue Aug 31, 2023 · 0 comments
Closed

Example is incorrect #19249

swork1 opened this issue Aug 31, 2023 · 0 comments
Labels
Unit: Documentation Bugs/feature requests, that are related to the documentations.

Comments

@swork1
Copy link

swork1 commented Aug 31, 2023

Describe the issue

The following example is incorrect. Running the following code gives me the output of
a -> [2, 2, 2, 2, 2, 3, 4]
b -> [2, 3, 13]

mut a := []int{len: 5, cap: 6, init: 2}
mut b := a[1..4]
a << 3
// no reallocation - fits in `cap`
b[2] = 13 // `a[3]` is modified
a << 4
// a has been reallocated and is now independent from `b` (`cap` was exceeded)
b[1] = 3 // no change in `a`
println(a) // `[2, 2, 2, 13, 2, 3, 4]`
println(b) // `[2, 3, 13]`

Updated code - requires the unsafe

mut a := []int{len: 5, cap: 6, init: 2}
mut b := unsafe { a[1..4] }
a << 3
// no reallocation - fits in `cap`
b[2] = 13 // `a[3]` is modified
a << 4
// a has been reallocated and is now independent from `b` (`cap` was exceeded)
b[1] = 3 // no change in `a`
println(a) // `[2, 2, 2, 13, 2, 3, 4]`
println(b) // `[2, 3, 13]`

Links

https://github.com/vlang/v/blob/master/doc/docs.md#array-slices

@swork1 swork1 added the Unit: Documentation Bugs/feature requests, that are related to the documentations. label Aug 31, 2023
Wertzui123 pushed a commit to Wertzui123/v that referenced this issue Oct 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Unit: Documentation Bugs/feature requests, that are related to the documentations.
Projects
None yet
Development

No branches or pull requests

1 participant