Common Go string processing tips

Guanhui
Release: 2020-06-12 18:35:54
forward
2523 people have browsed it

Common Go string processing tips

1. Multi-line strings

str := `This is a
multiline
string.`
Copy after login

Note - any indentation you put in the string will be retained in the final result.

str := `This string
    will have
    tabs in it`
Copy after login

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-"
}
Copy after login

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-"
}
Copy after login

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)
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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"))
}
Copy after login

虽然 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)
}
Copy after login

以上就是 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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template