Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a string in Go?

Tags:

go

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

I don't understand how a string can be a primitive type.

like image 682
ghigt Avatar asked Nov 28 '22 15:11

ghigt


1 Answers

A 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 this is not null terminated - the length is held in the len member.

So in C terms a go string is a long way from a primitive type, it is a pointer, a length and an area of memory.

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

like image 69
Nick Craig-Wood Avatar answered Dec 21 '22 22:12

Nick Craig-Wood