This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Other Languages and the fly likes Strings in Go Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Languages » Other Languages
Bookmark "Strings in Go" Watch "Strings in Go" New topic
Author

Strings in Go

Harald Schlindwein
Greenhorn

Joined: Jan 14, 2011
Posts: 2
Hi,


in Java it is a known problem to change strings at runtime especially in loops and very often.
That lead to StringBuilder/Buffer.

How does Go handle that problem or is there any for Go at all?

Given
var s string = "Some text"
var t string = "Some text"
would mean at runtime s == t in Java (afaik)
Also in Go? Because the byte field is the same and the compiler could/should know it...

Harald
Mark Summerfield
author
Ranch Hand

Joined: Jun 20, 2012
Posts: 37

Hi Harald,

In Go, strings are immutable just as they are in Java and Python. This has many benefits both in terms of performance and for writing robust concurrent programs.

Given
var s string = "Some text"
var t string = "Some text"
would mean at runtime s == t in Java (afaik)


This is an implementation detail that may or may not be true for any given JVM. The same applies in Python. In Go, s == t is true (== sensibly does the string comparison), but &s != &t (i.e., each has a different address so each string is unique). However, the address uniqueness is still just an implementation detail and shouldn't be assumed.

Go's equivalent to Java's StringBuilder is bytes.Buffer:



This assumes you have some readStringFromSomewhere() function that returns an empty string when it is finished. A slightly more sophisticated example is shown in "Programming in Go" on page 88.


Mark Summerfield
"Programming in Go" - http://www.qtrac.eu/gobook.html
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Strings in Go
 
Similar Threads
Journal Article - The SCJP Tip Line - Strings, Literally
StringTokenizer tab delimiter
Gc
Doubt on page 547 HFSJ
Go question: make(map) syntax