-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
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
A value from a map by key is a copy not a reference. #23618
Comments
Connected to Huly®: V_0.6-22042 |
This quirk caught me up these past few days in my project... It would be very nice to see it mentioned in the docs |
I think, that it may be a bug, i.e.: @medvednikov what do you think? |
I think V tries to help the programmer transforming sometimes a Another question is how expensive is the current copy or clone, say |
I check Golang, and also a map inspection returns a copy which can not be used for an accumulator. package main
import "fmt"
type accumulator struct {
data map[string][]int
}
func (a *accumulator) push(key string, value int) {
if copy, ok := a.data[key]; ok {
//copy = append(copy, value) DOES NOT WORK
_ = copy
a.data[key] = append(a.data[key], value) // WORKS
} else {
a.data[key] = make([]int, 0)
a.data[key] = append(a.data[key], value)
}
}
func main() {
a := &accumulator{
data: make(map[string][]int, 0),
}
for _, number := range []int{1, 2, 3, 4, 5} {
key := "odd"
if number%2 == 1 {
key = "even"
}
a.push(key, number)
}
fmt.Printf("data %v\n", a.data)
}
Again, I wonder how expensive is returning copies that cannot be used to accumulate specially when the values were big objects. I think V's mut could be a difference to return a non expensive reference and make this pattern more efficient. So this issue could be also a Feature request. Edit: there where errors with |
Describe the issue
I spend some time to realize that by getting a value from a map we get a copy instead a reference. So when we need to do an accumulator it will be fail if we try to update just the copy. Seems documentation is not clear about this:
I went to the docs to check how to detect a missing key but it doesn't say that the value found is a copy. The same happens using
if/else
oror { }
forms. Next program show the difference:Produces
Links
https://docs.vlang.io/v-types.html#maps
Note
You can use the 👍 reaction to increase the issue's priority for developers.
Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.
The text was updated successfully, but these errors were encountered: