Go strings, utf-8 and byte slices

Hi peeps, I am reading this Go blog about strings: https://go.dev/blog/strings

I tried playing around a bit and found that sample and sample[0] give a different output as below. I know a UTF-8 encoded Unicode character one-half should be “\xc2\xbd”, so the output of sample makes more sense to me. Can anyone help me understand why printing out a single byte produces the correct UTF-8 encoded character?

package main

import "fmt"

func main() {
    var sample = "\xbd"

    fmt.Println("Println:")
    fmt.Println(sample)
    fmt.Printf("%q, %q\n", sample, sample[0])
}```

Wait, I don’t quite understand what your question is? Are you wondering why %q ?
%q a double-quoted string safely escaped with Go syntax

see : fmt/format.go

// fmtQ formats a string as a double-quoted, escaped Go string constant.
// If f.sharp is set a raw (backquoted) string may be returned instead
// if the string does not contain any control characters other than tab.
func (f *fmt) fmtQ(s string) {
	s = f.truncateString(s)
	if f.sharp && strconv.CanBackquote(s) {
		f.padString("`" + s + "`")
		return
	}
	buf := f.intbuf[:0]
	if f.plus {
		f.pad(strconv.AppendQuoteToASCII(buf, s))
	} else {
		f.pad(strconv.AppendQuote(buf, s))
	}
}

You printing/converting different data types.

package main

import "fmt"

func main() {
	var sample = "\xbd"
	banana := sample[0]

	// DB hex = 189 decimal
	fmt.Printf("banana: %d \n", banana)

	// 189 decimal in string (ASCII table) = ½ https://www.ascii-code.com/CP1252/189
	fmt.Printf("%[1]s, %[1]q, %[2]q, %[2]U, %[1]T, %[2]T", sample, banana)
}

Output:
banana: 189
�, “\xbd”, ‘½’, U+00BD, string, uint8