[string] multiline stirng and break line "\n"

53 views
Skip to first unread message

Guilherme Dalmarco

unread,
Aug 21, 2020, 12:01:50 PM8/21/20
to golang-nuts
Why bytes.IndexByte can not find '\n' in multiline string?

package main

import (
"bytes"
"fmt"
)

func main() {
t1 := []byte("TEST\n")
t2 := []byte(`TEST\n`)
t3 := byte('\n')

fmt.Println(t1)
fmt.Println(t2)
fmt.Println(t3)

fmt.Println(bytes.IndexByte(t1, t3))
fmt.Println(bytes.IndexByte(t2, t3))
}

Jan Mercl

unread,
Aug 21, 2020, 12:06:29 PM8/21/20
to Guilherme Dalmarco, golang-nuts
Variable t2 has no newline in its value.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/925e3a5a-0775-44a4-8428-42b077a6be1dn%40googlegroups.com.

Axel Wagner

unread,
Aug 21, 2020, 12:23:49 PM8/21/20
to golang-nuts
Hey,

the `-quotes denote a "raw string literal". Escape-sequences in raw string literals are not interpreted - that's basically their purpose. So `t2` contains the literal two-byte sequence `\n`. You can see that in the output of `fmt.Println`, the newline is a 10, but t2 does not contain a 10, but a 92 ("\") and 110 ("n") instead.

If you want a raw string literal to contain an actual line-break, you have to put a line-break (not a line-break escape sequence) into it: https://play.golang.org/p/9DYfkVDk5RC

Hope that helps

--
Reply all
Reply to author
Forward
0 new messages