6 Tips for Using Strings in Go - Calhoun.io¶
チェック¶
- [ ] 本文を確認した
- [ ] 概要を確認した
- [ ] タグを確認した
- [ ]
inbox/直下へ移行した
概要¶
6 Tips for Using Strings in Go - Calhoun.io のWebクリップ。本文からGo、AWS、Observability、設計、キャリア評価などの学習材料として使えそうな内容を保存した。関連タグ: go, testing, web-clip。
本文¶
6 Tips for Using Strings in Go¶
string
1.Multiline strings¶
Run it on the Go Playground → https://play.golang.org/p/mpIQuNhC1kr
But be careful - any spacing you use in the string to retain indentation will also be present in the final string.
2.Efficient concatenation¶
strings.Builder
strings
bytes.Buffer
package main import ( "bytes" "fmt" ) func main() { var b bytes.Buffer for i := 0; i < 1000; i++ { b.WriteString(randString()) } fmt.Println(b.String()) } func randString() string { // Pretend to return a random string return "abc-123-" }
Run it on the Go Playground → https://play.golang.org/p/mtDENayW8dU
strings.Join
package main import ( "fmt" "strings" ) func main() { var strs []string for i := 0; i < 1000; i++ { strs = append(strs, randString()) } fmt.Println(strings.Join(strs, "")) } func randString() string { // Pretend to return a random string return "abc-123-" }
Run it on the Go Playground → https://play.golang.org/p/-nMvx3hKhwR
3.Convert ints (or any data type) into strings¶
"ID=#{id}"
"123"
"E"
fmt.Sprintf
strconv.Itoa
package main import ( "fmt" "strconv" ) func main() { i := 123 t := strconv.Itoa(i) fmt.Println(t) }
Run it on the Go Playground → https://play.golang.org/p/_q0n1NIgPZQ
package main import "fmt" func main() { i := 123 t := fmt.Sprintf("We are currently processing ticket number %d.", i) fmt.Println(t) }
Run it on the Go Playground → https://play.golang.org/p/DSJkfat7iAo
fmt.Printf
Sprintf
strconv
4.Creating random strings¶
This one isn’t really a “quick tip”, but it is a question I see asked a lot.
How do you create random strings in Go?
Sounds simple enough. Many languages like Ruby and Python provide some helpers that make generating a random string really easy, so surely Go has one, right? Wrong.
Rather than trying to provide all of these utilities, Go instead opts to provide building blocks to developers. As a result, you have a way to generate random data, but turning that into a string is left as an exercise to the developer. While this might be a turn off at first, the upside is that you get to completely dictate how the string is generated. This means you can dictate the character set, how your random generation is seeded, and any other pertinent details. In short, you have more control but at the cost of needing to write a little extra code.
Here is a quick example using the math/rand package and a set of alphanumeric characters as the character set.
package main import ( "fmt" "math/rand" "time" ) func main() { fmt.Println(RandString(10)) } const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func RandString(length int) string { r := rand.New(rand.NewSource(time.Now().UnixNano())) b := make([]byte, length) for i := range b { b[i] = charset[r.Intn(len(charset))] } return string(b) }
Run it on the Go Playground → https://play.golang.org/p/ocwA3yKS6he
The Go Playground always outputs the same string
2sdGzJ6rKk
rand.NewSource
crypto/rand
Regardless of what you end up using, this example should help get you started. It works well enough for most practical use cases that don’t involve sensitive data like passwords and authentication systems.
HasPrefix
sk_
For functions that sounds like very common use cases, your best bet is often to head on over to the strings package and check for something that might help you out. In this case you would want to use the functions strings.HasPrefix(str, prefix) and strings.HasSuffix(str, prefix). You can see them in action below.
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.HasPrefix("something", "some")) fmt.Println(strings.HasSuffix("something", "thing")) }
Run it on the Go Playground → https://play.golang.org/p/amPjDXejZJl
While there are a lot of useful common functions in the strings package, it is worth noting that it isn’t always worth digging around hunting for a package that does what you need. If you are picking up Go after having experience with another language, one common mistake I see is developers spending too much time looking for packages that provide the functionality that they need when they could have easily just written the code themselves.
There are definitely perks to using a standard library; Eg they are tested thoroughly and are well documented. Despite those perks, if you find yourself spending more than a few minute looking for a function it is often just as beneficial to write it yourself. In that case it will be customized for your needs, will be done quickly, and you will completely understand what is happening and won’t be caught off guard by weird edge cases. You also don’t have to worry about someone else maintaining the code.
6.Strings can be converted into byte slices (and vice versa)¶
The comments on reddit pointed out that the correlation between a string and byte slices isn’t always obvious, so while this article originally started out with 5 tips it has been expanded to 6.
[]byte
Below is an example of the conversions:
package main import "fmt" func main() { var s string = "this is a string" fmt.Println(s) var b []byte b = []byte(s) fmt.Println(b) for i := range b { fmt.Println(string(b[i])) } s = string(b) fmt.Println(s) }
Run it on the Go Playground → https://play.golang.org/p/D2lzr7BfAdX
And that’s it for tips on using strings in Go. I hope you found these helpful and informative, and be sure to check out some of my courses like Gophercises (info below) if you want to practice your Go a bit more.
Want to improve your Go skills?
Are you looking to practice Go, but can’t think of a good project to work on? Or maybe you just don’t know what techniques and skills you need to learn next, so you don't know where to start. If so, don’t worry - I’ve got you covered!
Gophercises is a FREE course where we work on exercise problems that are each designed to teach you a different aspect of Go. This includes topics ranging from basic string manipulation all the way to more advanced topics like functional options and concurrency. Each exercise has a sample solution, as well as a screencast (video) where I code the solution while walking you through the code. Plus, the Gophers are really cute 😉
Just getting started with Go?¶
Go is an awesome language whether you are new to programming or have experience in other languages, but learning a new language can be a struggle without the right resources.
To help save you time and get you off to a great start, I have created a guide to learning Go that you can get for FREE! Just sign up for my mailing list (down there ↓over there →) and I'll send it to your inbox.
You will also receive notifications when I release new articles and courses that I think will help you out while learning Go.
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
-
Testing is Not for Beginners
-
When nil Isn't Equal to nil
-
Concatenating and Building Strings in Go 1.10+
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.
要点¶
- Goの実装・設計・標準的な書き方を面接や実務の深掘り材料にする。
- 元URL: https://www.calhoun.io/6-tips-for-using-strings-in-go/