
1. Multi-line strings
str := `This is a multiline string.`
Note - any indentation you put in the string will be retained in the final result.
str := `This string
will have
tabs in it`2. Efficient string concatenation method
Go allows you to concatenate strings through " ", but this method will be very inefficient in scenarios where a large number of string concatenations are processed . Using bytes.Buffer to concatenate strings is a more efficient way, it will concatenate everything into a string at once.
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 {
// 模拟返回一个随机字符串
return "abc-123-"
}If you prepare all the strings in advance, you can also achieve it through 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 {
// 模拟返回一个随机字符串
return "abc-123-"
}3. Convert an integer (or any data type) to a string
In most languages, you can easily convert any data type to a string for splicing, or use String insertion (such as "ID=#{id}" in ruby). Unfortunately, if you try to do such an obvious operation in Go, such as forcing an integer to be converted to a string, you will not get the expected results.
i := 123 s := string(i)
What do you want the output of s to be? If you were like most people and guessed "123", you couldn't be more wrong. Instead, you'll get something like "E". This is not what we want at all!
Instead, you should use a package like [strconv] (https://golang.org/pkg/strconv/) or a function like fmt.Sprintf. For example, here is an example of using strconv.Itoa to convert an integer to a string.
package main
import (
"fmt"
"strconv"
)
func main() {
i := 123
t := strconv.Itoa(i)
fmt.Println(t)
}You can also use the fmt.Sprintf function to convert almost any data type to a string, but this should generally be reserved for instances where the string you are creating contains embedded data, not when you expect to Used when converting a single integer to a string.
package main
import "fmt"
func main() {
i := 123
t := fmt.Sprintf("We are currently processing ticket number %d.", i)
fmt.Println(t)
}Sprintf operates almost identically to fmt.Printf, except that instead of outputting the resulting string to standard output, it returns it as a string.
Restricted use of Sprintf
As mentioned before, fmt.Sprintf is usually used to create strings with embedded values. There are several reasons for this, but the most prominent one is that fmt.Sprintf doesn't do any type checking, so you're unlikely to find any errors before actually running the code.
Sprintf is also slower than most of the functions you typically use in the strconv package, although if I'm being honest the speed difference is so small that it's generally not worth considering.
4. Creating Random Strings
This isn’t really a “quick trick,” but I find it’s a question I get asked a lot.
How to create random strings in Go?
Sounds simple. Many languages, like Ruby and Python, provide helpers that make random string generation very easy, so Go must have such a tool, right? The answer is wrong.
Go has chosen to only provide tools for creating random strings, leaving the details to developers. While it may be a little difficult at first, the benefit is that you have full control over how you generate the string. This means you can specify the character set, how to seed the random generation, and any other details. In short, you have more control, but at the cost of writing some extra code.
Here's 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))
}
var source = rand.NewSource(time.Now().UnixNano())
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func RandString(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = charset[source.Int63()%int64(len(charset))]
}
return string(b)
}Go training ground always outputs the same string
If you run this code multiple times on the Go training ground, you may notice that it always outputs the same string -aJFLa7XPH5.
This is because the Go training ground always uses the same time, so when we use the rand.NewSource method. The value passed in the current time is always the same, so the string we generate is always the same.
There may be better solutions than this for your specific needs, but this is a good starting point. If you're looking for ways to improve/change your code, you might consider using the crypto/rand package to generate random data - this is generally safer, but may ultimately require more work.
No matter what you end up using, this example should help you get started. It works well enough for most practical use cases that don't involve sensitive data like passwords and authentication systems. Just be sure to remember to seed your random number generator! This can be done in the math/rand package via the rand.Seed function, or by creating a source code. In the example above, I chose to create a source code.
5. strings package, HasPrefix and custom code
When processing strings, you want to know whether a string starts with a specific string or ends with a specific string It's a very common situation. For example, if your API keys all start with sk_, then you may want to verify that all API keys provided in the API request start with this prefix, otherwise doing database lookups will waste a lot of time.
For those functions that sound like very common use cases, your best bet is usually to visit the strings package directly and check out a few things that might help you. In this case you will want to use the functions HasPrefix(str, prefix) and strings.HasSuffix(str, prefix). You can see their usage below.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.HasPrefix("something", "some"))
fmt.Println(strings.HasSuffix("something", "thing"))
}虽然 strings 包中有大量有用的公共函数,但值得注意的是,并不总是值得去寻找一个能满足您需要的包。如果你有其他语言经验正在学习 Go 语言,一个常见的错误是开发者花太多时间寻找能够提供所需功能的包,而他们自己可轻易地编码实现这功能。
使用标准库肯定有好处(如它们经过了彻底的测试并有很好的文档记录)。尽管有这些好处,但如果你发现自己花了超过几分钟的时间来寻找一个函数,那么自己编写它通常也是有益的。在这种情况下,根据需求自定义(编码),将很快完成,你将完全了解正在发生的事情,不会被奇怪的边界情况(译者注如索引越界)措手不及。您也不必担心其他人维护代码。
6. 字符串可以被转换成 byte 切片 (反之亦然)
Go 语言可以将一个字符串转换成 byte 切片 ([]byte) ,也可以将 byte 切片转换成字符串。转换的过程跟其他任意类型转换的方式一样简单。这种转换方式通常用于为一个接收 byte 切片参数的函数传递一个字符串 以及 为一个接收字符串参数的函数传递 byte 切片的场景。
下面是一个转换的例子:
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)
}以上就是 Go 语言字符串使用过程中的一些小技巧,希望能帮到你。如果你需要更多 Go 相关的实践,可以查阅我发表的其他相关教程。
推荐教程:《Go教程》
The above is the detailed content of Common Go string processing tips. For more information, please follow other related articles on the PHP Chinese website!
Choosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AMGolangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp
Golang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AMGolang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.
Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AMGolang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.
Golang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AMGolang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.
Golang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AMGo language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.
Golang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AMThe main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.
Golang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AMGolang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.
Golang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AMGolang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.






