-
Notifications
You must be signed in to change notification settings - Fork 17.8k
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
string: overly-lazy copy from []byte to string #67758
Comments
the first call to Closing because this behavior is permitted by the language spec. |
Yes, it's true that this is technically permitted by the language spec. When it says
it doesn't say anything about type conversions, which this technically is. However, it's no accident that the syntax for type conversion looks the same as the syntax for a function call, and in the case of Lines 75 to 80 in 9b43bfb
While that is of course an internal implementation detail, string(buf) looks like a function call, syntactically, and is in fact implemented as a function call, so I don't think it's unreasonable for someone to be surprised that this is undefined behavior.
In for example func idString1(b []byte) string { return string(b) }
type idString2 string
func cat(s1, s2 string) { return s1 + s2 }
r1 := cat(idString1(append(buf, x)), idString2(append(buf, y)))
r2 := cat(idString2(append(buf, x)), idString1(append(buf, y))) I think most people would be surprised that |
|
By the current spec, this is not a bug. It is just some counter-intuitive. BTW, the output of the following program changes (between Go toolchain 1.21 and 1.22). It is also not a bug. package main
func main() {
s := make([]byte, 0, 4)
s = append(s, "go"...)
defer println(
string(append(s, "od"...)),
string(append(s, "lf"...)),
)
} |
Go version
1.22
Output of
go env
in your module/workspace:What did you do?
https://go.dev/play/p/xHDQzbVo3W5
What did you see happen?
What did you expect to see?
I would expect for
to have identical behavior to
but it seems not to be the case here if
g()
isstring()
.The text was updated successfully, but these errors were encountered: