The Go language USES strings to share several tricks
- 2020-06-03 06:46:46
- OfStack
1. The bottom layer of a string is a one-byte array
This is really important and affects several other techniques below. When you create a string, it's essentially a 1-byte array. This means that you can access a single byte as if it were an array 1. For example, the following code prints each byte in a string and each byte in a corresponding byte array:
package main
import "fmt"
func main() {
str := "hello"
for i := 0; i < len(str); i++ {
fmt.Printf("%b %s\n", str[i], string(str[i]))
}
}
This is an important piece of knowledge, hence the second tip...
2. Use byte arrays or buffers to speed up string concatenation
In Go, strings are read-only, which means every time you use them
str = str + "something"
, a new string object is actually created. If you're looking for maximum code efficiency, use a byte buffer instead. For example:
package main
import (
"bytes"
"fmt"
)
func main() {
str := "something"
buf := bytes.NewBufferString(str)
for i := 0; i < 1000; i++ {
buf.Write([]byte(randomString()))
}
fmt.Println(buf.String())
}
func randomString() string {
ret := "pretend-this-is-random"
return ret
}
Using a byte array makes the above code a step more efficient, but you need to know the final string size. An intuitive example is in the Go language
left-pad
The implementation.
3. You can concatenate strings as you would any other array 1
When you want to intercept part 1 of a string, you can do this by intercepting part of an array.
package main
import "fmt"
func main() {
str := "XBodyContentX"
content := str[1 : len(str)-1]
fmt.Println(content)
}
4. Use the 'symbol to create multi-line strings
This is fairly simple. If you want to define a string containing multiple lines of address information in your code, you need to use the 'character, as shown below:
package main
import "fmt"
func main() {
str := `Mr. Smith
123 Something St
Some City, CA 94043`
fmt.Println(str)
}
5. You can embed the Unicode character in a string
Suppose you want to start with 0x00 and end with 0xFF when implementing WebSocket communication.
We can do this in any string by:
package main
import "fmt"
func main() {
str := "\x00BodyContent\xff"
fmt.Println(str)
}
Similarly, you can use Unicode strings for processing, or you can use raw characters in strings. For example, the following code is valid:
package main
import "fmt"
func main() {
a := "ÿay!"
b := "\u00FFay!"
fmt.Println(a, b)
}
conclusion
So much for the tips on using strings in Go. Have you learned them? I believe it will be very helpful for you to use Go language. If you have any questions, please leave a message.