What is a string in Go?

Is string in Go like char* in C (or a char[] ) or a string class in C ++ ... or something else?

I do not understand how a string can be a primitive type.

+4
source share
2 answers

The string in go is represented by this structure in C

 struct String { byte* str; intgo len; }; 

The str pointer points to the actual string data, but it is not terminated by zero - the length is stored in the len element.

Thus, in terms of C, the go string is long from a primitive type; it is a pointer, length, and memory area.

However, Go is not C, and all of these implementation details are invisible to Go programs. In Go, a string is a primitive immutable type.

+17
source

The documentation for type string says:

string is a set of all strings of 8-bit bytes, conditionally, but not necessarily representing UTF-8 encoded text. The string may be empty, but not null. String type values ​​are immutable.

They are immutable, which apparently makes them less like the C concepts you are comparing with, and more like const char [] , where const really means const .

Everything can be a primitive type in a programming language, right down to designers. To be primitive does not mean that you are, as you know, primitive. :)

+6
source

Source: https://habr.com/ru/post/1483734/


All Articles