If you are getting started with Go and find yourself asking questions like “why is this a byte array?” then you aren’t alone. It was one of the very first questions a friend studying computer science asked me when learning Go.
Here are a few tips to help make your life easier when dealing with strings in Go:
This is really important, and will come into play with several tips in this post. Anytime you create a string, under the hood you have an array of bytes. This means you can access individual bytes like you would an array. For example, the following code iterates over every byte in a string and prints it out as both a string and as a byte.
package main
import "fmt"
func main() {
str := "hello"
for i := 0; i < len(str); i++ {
fmt.Printf("%b %s\n", str[i], string(str[i]))
}
}
This is important because it leads us to our second tip…
Strings in go are readonly. What this means is that every time you write str = str + "something"
you are really creating a new string object. If you are looking to maximize the efficiency of your code you should use byte buffers instead. Here is an example:
package main
import (
"bytes"
"fmt"
)
func main() {
str := "something"
buf := bytes.NewBufferString(str)
for i := 0; i < 1000; i++ {
buf.Write([]byte(randomString()))
}
fmt.Println(buf.String())
}
func randomString() string {
ret := "pretend-this-is-random"
return ret
}
You can improve this even further by using byte arrays, but you would need to know the size of the final string. An example of when this might be the case is when writing left-pad in Go.
If you need to get the substring from a string you can do so by splicing it as if it were a character array. Example code is below.
package main
import "fmt"
func main() {
str := "XBodyContentX"
content := str[1 : len(str)-1]
fmt.Println(content)
}
This one is pretty simple. Lets say you want to want to hard code an address into your code you could do so with the back tick. Here is an example:
package main
import "fmt"
func main() {
str := `Mr. Smith
123 Something St
Some City, CA 94043`
fmt.Println(str)
}
Lets say you are writing your own implementation of websockets, you need to start your data with the byte 0x00
and end with the byte 0xFF
[source].
If you want to you can easily embed this into any strings like so:
package main
import "fmt"
func main() {
str := "\x00BodyContent\xff"
fmt.Println(str)
}
Similarly, you can also do this with unicode characters, or you can use the raw character in your string. For example, both of the following are valid:
package main
import "fmt"
func main() {
a := "ÿay!"
b := "\u00FFay!"
fmt.Println(a, b)
}
Did you find this article helpful? If so, I recommend checking out the related article, . In the article we cover additional ways to use strings more effeciently, though there is some overlap with this article.
Sign up for my mailing list and I'll send you a FREE sample from my course - Web Development with Go. The sample includes 19 screencasts and the first few chapters from the book.
You will also receive emails from me about Go coding techniques, upcoming courses (including FREE ones), and course discounts.
Jon Calhoun is a full stack web developer who teaches about Go, web development, algorithms, and anything programming. If you haven't already, you should totally check out his Go courses.
Previously, Jon worked at several statups including co-founding EasyPost, a shipping API used by several fortune 500 companies. Prior to that Jon worked at Google, competed at world finals in programming competitions, and has been programming since he was a child.
Related articles
Spread the word
Did you find this page helpful? Let others know about it!
Sharing helps me continue to create both free and premium Go resources.
Want to discuss the article?
See something that is wrong, think this article could be improved, or just want to say thanks? I'd love to hear what you have to say!
You can reach me via email or via twitter.
©2024 Jonathan Calhoun. All rights reserved.