gpt4 book ai didi

go - 了解字符串转义序列

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:52 25 4
gpt4 key购买 nike

我是新手,所以对字节概念有很多困惑。

在浏览一些 go 代码时,我遇到了类似的事情

[]byte("\xd2\xfd\x88g\xd5\r-\xfe")

它是十六进制还是字节格式?

上面的g,r-,e等字符代表什么?

以及如何在日志中打印出来?

最佳答案

[]byte("\xd2\xfd\x88g\xd5\r-\xfe") 是转换为 []byte 类型的解释字符串文字,一个byte slice 。这里它被分成字节值:

[\xd2, \xfd, \x88, g, \xd5, \r, -, \xfe]

或者,以十六进制字节表示,

[d2, fd, 88, 67, d5, 0d, 2d, fe]

记录值的一种方法,

package main

import "log"

func main() {
b := []byte("\xd2\xfd\x88g\xd5\r-\xfe")
log.Printf("%q\n", b)
}

Playground :https://play.golang.org/p/BIh_EuvoxU-

输出:

2009/11/10 23:00:00 "\xd2\xfd\x88g\xd5\r-\xfe"

The Go Programming Language Specification


String literals

A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals.

Raw string literals are character sequences between back quotes, as in foo. Within the quotes, any character may appear except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines. Carriage return characters ('\r') inside raw string literals are discarded from the raw string value.

Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear except newline and unescaped double quote. The text between the quotes forms the value of the literal, with backslash escapes interpreted as they are in rune literals (except that \' is illegal and \" is legal), with the same restrictions. The three-digit octal (\nnn) and two-digit hexadecimal (\xnn) escapes represent individual bytes of the resulting string; all other escapes represent the (possibly multi-byte) UTF-8 encoding of individual characters. Thus inside a string literal \377 and \xFF represent a single byte of value 0xFF=255, while ÿ, \u00FF, \U000000FF and \xc3\xbf represent the two bytes 0xc3 0xbf of the UTF-8 encoding of character U+00FF.


After a backslash, certain single-character escapes represent special values:

\a   U+0007 alert or bell
\b U+0008 backspace
\f U+000C form feed
\n U+000A line feed or newline
\r U+000D carriage return
\t U+0009 horizontal tab
\v U+000b vertical tab
\\ U+005c backslash
\' U+0027 single quote (valid escape only within rune literals)
\" U+0022 double quote (valid escape only within string literals)

关于go - 了解字符串转义序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50923059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com