Share 6 Go tips for handling strings

  • 2020-08-22 22:12:08
  • OfStack

If you make the transition from Ruby or Python to Go, there will be many language differences to learn, many of which revolve around dealing with string types.

Here are 1 string tricks that solved the problems I encountered during the first few weeks of using Golang.

1. Multi-line string

Creating multi-line strings in Go is very easy. Only use (' ') when you declare or assign a value.


str := `This is a
multiline
string.`

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


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

2. Efficient string concatenation

Go allows you to "+" string concatenation, but this approach is very inefficient in the case of a large number of concatenations. Using the bytes.Buffer concatenation string is a more efficient way to concatenate everything into a string once and for all.


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 {
  //  Simulation of return 1 Random string 
  return "abc-123-"
}

If you have all the strings ready in advance, you can also do this via ES30en.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 {
  //  Simulation of return 1 Random string 
  return "abc-123-"
}

3. Converts an integer (or any data type) to a string

In most languages, any data type can be easily transformed into a string for concatenation or inserted as a string (for example, "ID=#{id}" in ruby). Unfortunately, if you try to do this visually obvious operation in Go, such as forcing the plastic to turn into a string, you won't get the desired result.


i := 123
s := string(i)

What do you want the output of s to be? If, like most people, you guessed "123", you would be dead wrong. Instead, you get something like "E". That's not what we want!

Instead, you should use like [strconv] (https: / / golang org pkg/strconv /) such a package or as fmt.. Sprintf such function. For example, here is an example of using ES57en.Itoa to convert integers to strings.


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 you should usually keep it on instances where 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 := fmt.Sprintf("We are currently processing ticket number %d.", i)
  fmt.Println(t)
}

Sprintf does almost the same thing as ES68en.Printf, except instead of printing the result string to standard output, it returns it as a string.

Limit use of Sprintf

As mentioned earlier, fmt.Sprintf is commonly used to create strings with embedded values. There are several reasons for this, but the most prominent one is that fmt.Sprintf does not do any type checking, so you are unlikely to find any errors until you actually run the code.

Sprintf is also slower than most of the functions you normally use in strconv packages, but if I'm being honest, the speed difference is so small that it's hardly worth considering.

4. Create random strings

This isn't really a "quick trick," but It's a question I've found to be asked a lot.

How do I create a random string in Go?

Sounds simple enough. Many languages, such as Ruby and Python, provide a helper program that makes random string generation very easy, so Go must have one, right? The answer is wrong.
Go chose to provide only the tools to create random strings, leaving the details to the developers. Although 1 May be a little difficult at first, the advantage is that you can completely decide how to generate the string. This means that you can specify character sets, how to seed random generation, and any other details. In short, you have more control, but at the cost of writing a little extra code.

Below is a quick example of a character set that USES the math/rand package and a set of alphanumeric characters.


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)
}

The Go range always outputs the same string

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

This is because the Go range always USES the same time, so when we use the ES114en.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 a better solution than this for your specific needs, but it's a good place to start. If you're looking for ways to improve/change your code, you might want to consider using the crypto/rand package to generate random data -- this is usually more secure, but may ultimately require more work.

Whatever you end up using, this example should get you started. It works well enough for most practical use cases that do not involve sensitive data such as passwords and authentication systems. Just 1 remember your seed random number generator! This can be done in the math/rand package with the ES122en.Seed function, or by creating a source code. In the above example, I chose to create 1 source code.

strings package, HasPrefix and custom code

When dealing with strings, it is very common to want to know whether a string starts with a particular string or ends with a particular string. For example, if your API keys all start with sk_, you might want to verify that all the API keys provided in the API request start with this prefix, otherwise doing a database lookup would be a waste of time.

For functions that sound like very common use cases, your best bet is usually to go directly to the strings package and check for something that might help you. In this case, you would want to use the functions HasPrefix(str, prefix) and ES143en.HasSuffix (str, prefix). You can see how they are used below.


package main

import (
  "fmt"
  "strings"
)

func main() {
  fmt.Println(strings.HasPrefix("something", "some"))
  fmt.Println(strings.HasSuffix("something", "thing"))
}

While the strings package contains a number of useful public functions, it is worth noting that it is not always worth finding a package that meets your needs. If you have experience with other languages and are learning Go, a common mistake is for developers to spend too much time looking for packages that provide the functionality they need, when they can easily code for it themselves.

There are definitely benefits to using standard libraries (such as they are thoroughly tested and well documented). Despite these benefits, if you find yourself spending more than a few minutes looking for a function, it's often beneficial to write it yourself. In this case, customizing (coding) according to requirements will be done quickly and you will be fully aware of what is going on and will not be caught off guard by strange boundary conditions. You also don't have to worry about someone else maintaining the code.

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

The Go language can convert 1 string into an byte slice ([]byte) or a byte slice into a string. The process of conversion is as simple as any other type of conversion. This conversion is typically used in scenarios where 1 string is passed for a function that receives an byte slice argument and 1 byte slice is passed for a function that receives a string argument.

Here is an example of a transformation:


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)
}

These are the tips for using Go language strings. I hope they will help you. If you need more practice on Go, check out the other tutorials I've published.

The original address: https: / / www calhoun. io / 6 - tips - for - using strings -- in go /


Related articles: