emahiro/b.log

Drastically Repeat Yourself !!!!

Go の string についてなんとなく調べた

Overview

ちょっと興味があって Go の string の実装周りについてふらっと調べたので備忘録。
そのほかにも何かわかれば追記するかも。

Memo

string 本体について

string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. A string may be empty, but not nil. Values of string type are immutable.

ref: https://pkg.go.dev/builtin#string

Go の文字列そのものは 8-bit の byte 配列の文字列の集合。

実行環境での string の実体については以下

// StringHeader is the runtime representation of a string.
// It cannot be used safely or portably and its representation may
// change in a later release.
// Moreover, the Data field is not sufficient to guarantee the data
// it references will not be garbage collected, so programs must keep
// a separate, correctly typed pointer to the underlying data.
type StringHeader struct {
    Data uintptr
    Len  int
}

ref: https://golang.org/src/reflect/value.go

データ = 文字列の中身を表す参照と長さの情報を持っている。GC から守られてるわけではない(GCで回収されうる)