0
0

More than 3 years have passed since last update.

【Golang】空の rune をセットする(はたまた rune の初期化)

Posted at

空のルーン文字を返したいが、返り血をあびるし、戻り値で吐血する

""で切り返すと返り血をあびる
func Foo() (rune, error) {
    err := errors.New("my error")

    return "", err
}
// Output: cannot use "" (untyped string constant) as rune value in return statement
new()で戻すと吐血する
func Bar() (rune, error) {
    err := errors.New("my error")

    return new(rune), err
}
// Output: cannot use new(rune) (value of type *rune) as rune value in return statement
nilても焼いても食えない
func Buzz() (rune, error) {
    err := errors.New("my error")

    return nil, err
}
// Output: cannot use nil (untyped nil value) as rune value in return statement

「"golang" 空のruneをセットする」でググっても Golang 初心者でせっかちなものだからピンポイントでタイトルからわかる記事が出てこなかったので、未来の自分のググラビリティのため。

TL; DR (今北産業)

  1. 0(ゼロ)を返す。(例:return 0, err
  2. runeの初期値である0(ゼロ)を返す
    func Hoge() (rune, error) {
        err := errors.New("my error")
    
        return 0, err
    }
    
  3. runeint32 型のエイリアスですが、Unicode の 1 文字分の文字コードコードポイントを格納できます。

  4. 文字列とルーン文字の違い

    • Go のソースコードは常に UTF-8 です。
    • 文字列は任意のバイトを保持します。
    • 文字列リテラルは、バイトレベルのエスケープがなくても、常に有効なUTF-8シーケンスを保持します。
    • これらの配列は、runeルーンと呼ばれる Unicode コードポイントを表します。
    • Go では、文字列内の文字が正規化されることは保証されていません。

TS; DR (ドキュメントを嫁にしたい未来の自分に)

"Code point" is a bit of a mouthful, so Go introduces a shorter term for the concept: rune. The term appears in the libraries and source code, and means exactly the same as "code point", with one interesting addition.
The Go language defines the word rune as an alias for the type int32, so programs can be clear when an integer value represents a code point. Moreover, what you might think of as a character constant is called a rune constant in Go. The type and value of the expression

'⌘'

is rune with integer value 0x2318.
Code points, characters, and runes | Strings, bytes, runes and characters in Go @ Go 公式ブログ より)

【筆者訳】
"code point" という言葉は、いささか言いにくいため Go ではこの概念を短くした "runeルーン" という言葉を導入しています。この用語はライブラリやソースコードに登場し、Unicode の「コードポイント符号位置」とまったく同じ意味を持ちます。しかし、1 つ面白いことが追加されています。

Go 言語では int32 型の別名(エイリアス)として rune という言葉を定義しています。そのため、プログラム内で整数値がコードポイントを表すかどうかを明確にすることができます。さらに、一般的に文字コードと考えられているものは、Go ではルーン定数rune constantと呼ばれます。
例えば、"" という文字をコードで表現する場合、型と値は「rune 型」で「値が整数の 0x2318」と表現できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0