When to use []byte or string in Go?

后端 未结 3 1996
眼角桃花
眼角桃花 2021-01-31 01:05

Frequently in writing Go applications, I find myself with the choice to use []byte or string. Apart from the obvious mutability of []byte,

3条回答
  •  野性不改
    2021-01-31 02:06

    I've gotten the sense that in Go, more than in any other non-ML style language, the type is used to convey meaning and intended use. So, the best way to figure out which type to use is to ask yourself what the data is.

    A string represents text. Just text. The encoding is not something you have to worry about and all operations work on a character by character basis, regardless of that a 'character' actually is.

    An array represents either binary data or a specific encoding of that data. []byte means that the data is either just a byte stream or a stream of single byte characters. []int16 represents an integer stream or a stream of two byte characters.

    Given that fact that pretty much everything that deals with bytes also has functions to deal with strings and vice versa, I would suggest that instead of asking what you need to do with the data, you ask what that data represents. And then optimize things once you figure out bottlenecks.

    EDIT: This post is where I got the rationale for using type conversion to break up the string.

提交回复
热议问题