String Byte Slice Conversion Copies

Converting between string and []byte copies the data each way, so byte-slice edits never touch the original string, and len counts UTF-8 bytes not runes.

GoData Integrity

Code

gosnippet
19 lines
package main

import "fmt"

func main() {
	s := "café"

	// string → []byte 会发生一次完整拷贝:改字节不影响原字符串
	b := []byte(s)
	b[1] = 'o'
	fmt.Println("original:", s, "modified:", string(b))

	// []byte → string 同样是一次拷贝,得到独立的新值
	back := string(b)
	fmt.Println("converted:", back)

	// 字符串不可变:没有合法途径原地改写字节;len 按 UTF-8 字节计
	fmt.Println("utf8 bytes:", len(s), "runes:", len([]rune(s)))
}

What the code does

Count the function main as the entire surface area of String Byte Slice Conversion Copies.

Applying it

Running the file prints labeled results such as original:, converted:, utf8 bytes: — each operation’s effect is visible in the output.

Statements that matter

back := string(b)

Interactive Tools for This Topic

FAQ

What does String Byte Slice Conversion Copies print when run?
Running the file directly is enough — expect labeled output lines such as `original:`, `converted:`, `utf8 bytes:`.