What is a string in Go?

huangapple go评论86阅读模式
英文:

What is a string in Go?

问题

Go中的“string”类型类似于C中的“char*”(或“char[]”)或C++中的类“string”吗?还是其他什么东西?

我不明白一个字符串如何成为原始类型。

英文:

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.

答案1

得分: 17

在Go中,字符串是由C中的这个结构表示的:

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

str指针指向实际的字符串数据,但它没有以空字符结尾 - 长度保存在len成员中。

因此,从C的角度来看,Go字符串与原始类型相差甚远,它是一个指针、一个长度和一块内存区域。

然而,Go不是C,所有这些实现细节对Go程序是不可见的。在Go中,字符串是一种原始的不可变类型。

英文:

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.

答案2

得分: 6

string类型的文档中说:

> string是由所有8位字节组成的字符串集合,通常但不一定表示UTF-8编码的文本。字符串可以为空,但不能为nil。string类型的值是不可变的。

它们是不可变的,这似乎使它们与你进行比较的C概念不太相似,更像是const char [],其中的const确实意味着const

在编程语言中,任何东西都可以是原始类型,这取决于设计者。"作为原始类型"并不一定意味着实际上是原始的,你知道的。 What is a string in Go?

英文:

The documentation for the type string says:

> 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.

They are immutable, which would seem to make them less like the C concepts you compare to, and more like maybe a const char [] where the const really means const.

Anything can be a primitive type in a programming language, it's up to the designers. "Being a primitive" doesn't have to mean actually being, you know, primitive. What is a string in Go?

huangapple
  • 本文由 发表于 2013年5月31日 15:41:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/16852218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定