Golang : Convert(cast) string to uint8 type and back to string
Problem :
You have a variable of type string and you want to convert/type cast it to uint8 type.
Solution :
If you plan to convert a single character, then type cast it with uint8()
function. If the string is couple of characters, use []uint8()
instead.
For example :
package main
import (
"fmt"
"reflect"
)
var str string = "this is a string"
func main() {
fmt.Printf("The value of test is %s \n", str)
fmt.Printf("The type of test is %v \n", reflect.TypeOf(str))
newStr := []uint8(str)
fmt.Printf("The value of newStr is %s \n", newStr)
fmt.Printf("The type of newStr is %v \n", reflect.TypeOf(newStr))
// convert back to string
backToStr := string([]byte(newStr[:]))
fmt.Println(backToStr)
fmt.Printf("The value of backToStr is [%s] \n", backToStr)
fmt.Printf("The type of backToStr is %v \n", reflect.TypeOf(backToStr))
}
Output :
The value of test is this is a string
The type of test is string
The value of newStr is this is a string
The type of newStr is []uint8
this is a string
The value of backToStr is [this is a string]
The type of backToStr is string
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
+7.1k Prevent Write failed: Broken pipe problem during ssh session with screen command
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+28k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+48.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+7.7k Golang : Simple histogram example
+6.2k Golang : How to stop user from directly running an executable file?
+19.6k Golang : How to read float value from standard input ?
+15.3k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+9.6k Golang : Bubble sort example
+25.7k Golang : Convert CSV data to JSON format and save to file
+5k Golang : How to write backslash in string?
+4.5k Golang : fmt.Println prints out empty data from struct