【转】go里面字符串转成 字节slice, 字节slice转成字符串

原文: https://yourbasic.org/golang/convert-string-to-byte-slice/#convert-string-to-bytes

---------------------------------------------------------------------------

yourbasic.org/golang
Golang gopher

Basics

When you convert between a string and a byte slice (array), you get a brand new slice that contains the same bytes as the string, and vice versa.

  • The conversion doesn’t change the data;
  • the only difference is that strings are immutable, while byte slices can be modified.

If you need to manipulate the characters (runes) of a string, you may want to convert the string to a rune slice instead. See Convert between rune array/slice and string.

Convert string to bytes

When you convert a string to a byte slice, you get a new slice that contains the same bytes as the string.

b := []byte("ABC€")
fmt.Println(b) // [65 66 67 226 130 172]

Note that the character  is encoded in UTF-8 using 3 bytes. See the Go rune articlefor more on UTF-8 encoding of Unicode code points.

Convert bytes to string

When you convert a slice of bytes to a string, you get a new string that contains the same bytes as the slice.

s := string([]byte{65, 66, 67, 226, 130, 172})
fmt.Println(s) // ABC€

Performance

These conversions create a new slice or string, and therefore have time complexityproportional to the number of bytes that are processed.

More efficient alternative

In some cases, you might be able to use a string builder, which can concatenate strings without redundant copying:

转载于:https://www.cnblogs.com/oxspirt/p/11279077.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值