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
+20.5k error: trying to remove "yum", which is protected
+21.8k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+10.5k Golang : convert(cast) string to float value
+1.5k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+5.1k Golang : Convert decimal number(integer) to IPv4 address
+19k Golang : How to write CSV data to file
+3.9k Golang : Qt Yes No and Quit message box example
+3.5k Golang : Scramble and unscramble text message by randomly replacing words
+2.7k Golang : Humanize and Titleize functions
+2.5k PHP : Hide PHP version information from curl
+17.8k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+5k Golang : Secure file deletion with wipe example