Golang : convert(cast) bytes to string
Encounter a problem when helping out a co-worker today to read in data generated by another program. To make it short, the data is in the form of array of bytes and the objective is to convert the bytes into string. The problem is that the length of the given data is dynamic and we need to create a program that can handle the dynamic length.
Typically, the program should look something like 1st program below
1st program :
package main
import "fmt"
func main() {
src := [10]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}
fmt.Println(len(src), src)
dst := string(src[:])
fmt.Println(len(dst), dst)
}
and running this program will generate error array index 10 out of bounds [0:10]
and to fix the error.... a programmer will typically just increase the array size.... which in turn... it will work ... but also generate trailing zeros 20 [104 101 108 108 111 32 119 111 114 108 100 0 0 0 0 0 0 0 0 0]
.
What if there is a incoming array of higher values ? Then the error will appear again.
In Golang, there is a better way to handle this kind of dynamic length situation. We will use the three dots to tell the compiler to figure out the length of the array during run time.
2nd program :
package main
import "fmt"
func main() {
src := [...]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}
fmt.Println(len(src), src)
dst := string(src[:])
fmt.Println(len(dst), dst)
}
Output :
11 [104 101 108 108 111 32 119 111 114 108 100]
11 hello world
Hope this will assist you in developing a more robust program.
See also : Golang : automatically figure out array length(size) with three dots
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.6k Golang : Gaussian blur on image and camera video feed examples
+4.9k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+11.8k Golang : Detect user location with HTML5 geo-location
+14.3k Golang : How to get URL port?
+7.3k Golang : Detect sample rate, channels or latency with PortAudio
+7.3k Golang : Gorrila set route name and get the current route name
+5.8k Fontello : How to load and use fonts?
+6.5k Golang : Derive cryptographic key from passwords with Argon2
+8.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+12k Golang : List running EC2 instances and descriptions
+14.7k Golang : Search folders for file recursively with wildcard support
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character