SoFunction
Updated on 2025-03-03

Share 6 tips for Go processing strings

If you transition from Ruby or Python to Go, there will be a lot of language differences to learn, and many of these problems revolve around dealing with string types.

Here are some string tips that solve the problems I had in my first few weeks with Golang.

1. Multi-line string

Creating multi-line strings in Go is very easy. Just use (``) when you declare or assign values.

str := `This is a
multiline
string.`

Note - Any indentation you have in the string will be kept in the final result.

str := `This string
  will have
  tabs in it`

2. Efficient string connection method

Go allows you to concatenate strings by "+", but this method will be very inefficient in handling large number of string concatenations. Using concatenating strings is a more efficient way to concatenate everything into strings at once.

package main

import (
  "bytes"
  "fmt"
)

func main() {
  var b 

  for i := 0; i < 1000; i++ {
    (randString())
  }

  (())
}

func randString() string {
  // Simulation returns a random string  return "abc-123-"
}

If you prepare all the strings in advance, you can do it in the same way as .

package main

import (
  "fmt"
  "strings"
)

func main() {
  var strs []string

  for i := 0; i < 1000; i++ {
    strs = append(strs, randString())
  }

  ((strs, ""))
}

func randString() string {
  // Simulation returns a random string  return "abc-123-"
}

3. Convert integer (or any data type) to string

In most languages, it is easy to transform any data type into strings for splicing or inserting with strings (for example, "ID=#{id}" in ruby). Unfortunately, if you try to do this visible operation in Go, such as forcing the shaping to a string, you won't get the desired result.

i := 123
s := string(i)

What do you want the output of s? If you guess "123" like most people, you're very wrong. Instead, you get a value similar to "E". This is not what we want at all!

Instead, you should use something like [strconv] (/pkg/strconv/) such package or functions like this. For example, the following is an example of using : to convert integers to strings.

package main

import (
  "fmt"
  "strconv"
)

func main() {
  i := 123
  t := (i)
  (t)
}

You can also use the function to convert almost all data types to strings, but it should usually be left on instances like the string being created contains embedded data, rather than when you expect to convert a single integer to a string.

package main

import "fmt"

func main() {
  i := 123
  t := ("We are currently processing ticket number %d.", i)
  (t)
}

Sprintf operates almost the same as , except that it does not output the result string to standard output, but returns it as a string.

Restricting Sprintf

As mentioned earlier, it is usually applied to create strings with embedded values. There are several reasons for this, but the most prominent one is that you don't do any type checking, so you're unlikely to find any errors before actually running the code.

Sprintf is also slower than most functions you usually use in the strconv package, but if I'm honest, the speed difference is so small that it's generally not worth considering.

4. Create a random string

It's not really a "quick trick", but I find it's a question that is often asked.

How to create a random string in Go?

It sounds simple. Many languages, such as Ruby and Python, provide some helpers to make the generation of random strings very simple, so Go must have such a tool, right? The answer is wrong.
Go chooses to provide only tools to create random strings, leaving details to developers. While it may be a bit difficult at first, the benefit is that you can completely decide how to generate the string. This means you can specify the character set, how to seed random generation, and any other details. In short, you have more control, but the price is to write some extra code.

Here is a usemath/rand A quick example of a package and a set of alphanumeric characters as a character set.

package main

import (
  "fmt"
  "math/rand"
  "time"
)

func main() {
  (RandString(10))
}

var source = (().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 driving range always outputs the same string

If you run this code multiple times on the Go driving field, you may notice that it always outputs the same string - aJFLa7XPH5.

This is because the Go driving range always uses the same time, so when we use the method. The value passed in the current time is always the same, so the string we generate is always the same.

There may be a better solution than this for your specific needs, but this is a great starting point. If you are looking for ways to improve/change your code, you might consider using the crypto/rand package to generate random data—this is usually safer, but may require more work in the end.

Whatever 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 your seed random number generator! This can be done by function in the math/rand package, 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 working with strings, it is very common to know whether a string starts with a specific string or ends with a specific string. For example, if your API keys all start with sk_, you may want to verify that all API keys provided in your API request start with this prefix, otherwise doing a database lookup will be a lot of time.

For functions that sound like very common use cases, your best bet is usually direct accessstrings Pack and check out some content that might help you. In this case, you'll want to use the functionHasPrefix(str, prefix) and(str, prefix). You can see their usage below.

package main

import (
  "fmt"
  "strings"
)

func main() {
  (("something", "some"))
  (("something", "thing"))
}

Although there are a lot of useful public functions in the strings package, it is worth noting that it is not always worth looking for a package that meets your needs. If you have experience in other languages ​​learning Go, a common mistake is that developers spend too much time looking for packages that provide the required functionality, which they can easily code to implement.

There are certainly benefits to using standard libraries (like they are thoroughly tested and well documented). Despite these benefits, it is usually beneficial to write it yourself if you find yourself spending more than a few minutes looking for a function. In this case, customizing (encoding) according to the needs will be done quickly, and you will fully understand what is going on and will not be caught off guard by the strange boundary situation. You don't have to worry about others maintaining the code.

6. Strings can be converted into byte slices (and vice versa)

Go can convert a string into a byte slice ([]byte) or convert a byte slice into a string. The conversion process is as simple as any other arbitrary type conversion method. This conversion method is usually used in scenarios where a string is passed to a function that receives a byte slice parameter and a byte slice for a function that receives a string parameter.

Here is an example of a conversion:

package main

import "fmt"

func main() {
  var s string = "this is a string"
  (s)
  var b []byte
  b = []byte(s)
  (b)
  for i := range b {
    (string(b[i]))
  }
  s = string(b)
  (s)
}

The above are some tips in the process of using Go language strings, I hope they can help you. If you need more Go-related practices, you can check out other related tutorials I have published.

Original address:/6-tips-for-using-strings-in-go/

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.