Hi, neither is *always* the case. One example of where no allocation is done is when converting a []byte into a string to use as a map-index, as long as a) it is done in one expression and b) the key doesn't have to be stored (i.e. the access is read-only):
b := []byte{70,111,111} m := make(map[string]int) v := m[string(b)] // does not allocate And as always, a conversion might end on the stack, if the compiler can prove that the storage doesn't have to survive the call, e.g. x := "Hello world" os.Stdout.Write([]byte(x)) // does not escape (note, that in this example, it's important that `os.Stdout` is an `*os.File`, not just an `io.Writer`, so the compiler actually knows the real function that is called). But, in general, I think you can assume that such a conversion has to allocate and I'd guess that in most cases, it needs to go on the heap. You can use `-gcflags=-m` to see if a particular conversion allocates or not. On Fri, Jan 29, 2021 at 1:55 PM xie cui <cuiwei...@gmail.com> wrote: > I mean convert using > s := "abcefg" > b := []byte(s) > s2 := string(b) > > not convert using some unsafe.Pointer trick. > > On Friday, January 29, 2021 at 8:51:57 PM UTC+8 xie cui wrote: > >> does convert string to []byte, and convert []byte to string alway alloc >> new space, and the new space is in heap? >> if it is not, please show some demo codes? >> > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/18219e42-1a46-42ba-a28b-2b432ccc0a40n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/18219e42-1a46-42ba-a28b-2b432ccc0a40n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAEkBMfF6PeC0%3D1dtK9Rp9yNwWHbsaTwdeQ%3DSsrgBdOWSs%3D_0%3DA%40mail.gmail.com.