如何将转义序列的字符串转换为字节?

huangapple go评论92阅读模式
英文:

How do I convert a string of escape sequences to bytes?

问题

创建一个需要处理一些数据的TCP服务器。我有一个net.Conn实例"connection",我将从中读取数据。代码片段的下半部分出现了一个错误,指出无法将'esc'值用作字节值。

const (
    esc = "\a\n"
)
....
c := bufio.NewReader(connection)
data, err := c.ReadBytes(esc)

显然,需要进行一些转换,但是当我尝试以下代码时:

const (
    esc = "\a\n"
)
....
c := bufio.NewReader(connection)
data, err := c.ReadBytes(byte(esc))

编译器指出我无法将esc转换为字节。这是因为我在包级别上将"\a\n"声明为const值吗?还是与我如何构造要读取的字节有关的其他问题?

英文:

Creating a TCP server that needs to process some data. I have a net.Conn instance "connection"from which I will read said data. The lower part of the snippet brings about an error noting that it cannot use the 'esc' value as a byte value.

const(
esc = "\a\n"
 )
....
c := bufio.NewReader(connection)
data, err := c.ReadBytes(esc)

Clearly, some conversion is needed but when I try

 const(
esc = "\a\n"
 )
....
c := bufio.NewReader(connection)
data, err := c.ReadBytes(byte(esc))

The compiler makes note that I cannot convert esc to byte. Is it due to the fact that I declared "\a\n" as a const value on the package level? Or is there something else overall associated with how I'm framing the bytes to be read?

答案1

得分: 1

你无法将esc转换为byte,因为你无法将字符串转换为单个字节。你可以将字符串转换为字节切片([]byte)。

bufio.Reader仅支持单字节分隔符,如果要处理多字节分隔符,你应该使用带有自定义分割函数的bufio.Scanner

也许可以修改 https://stackoverflow.com/a/37531472/1205448 的代码来实现。

英文:

You can't convert esc to byte because you can't convert strings into single bytes. You can convert a string into a byte slice ([]byte).

The bufio.Reader only supports single byte delimiters, you should use a bufio.Scanner with a custom split function instead for multi-byte delimiters.

Perhaps a modified version of https://stackoverflow.com/a/37531472/1205448

huangapple
  • 本文由 发表于 2022年4月19日 20:18:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/71924815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定