Nov 112017

ADM

How to convert a string to an unsigned int type in Golang

  • November 11 2017
  • ADM

 

 

How to convert a string to an unsigned int type in Golang - golang

 

Here is a simple snippet how to convert a string into an unsigned int type in Golang. If you need help how to install Golang check the references links.

Code

To convert a string to an unsigned int you can use the method strconv.ParseUint. ParseUint interprets a string s in the given base (2 to 36) and returns the corresponding value i.

package main

import (
	"fmt"
	"strconv"
)

func main() {

	str := "1234"

	/** converting the str1 variable into an unsigned int using ParseUint method */
	i, err := strconv.ParseUint(str, 10, 64)
	if err == nil {
		fmt.Printf("Type: %T \n", i)
		fmt.Println(i)
	}
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build string_to_uint.go

Then depending if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ string_to_uint

Windows

c:\Users\adm\go\tutorials> string_to_uint.exe

If you want to compile and run the application in one single step run the following command:

go run string_to_uint.go

Output

Will display the i variables types and the corresponding values.

Type: uint64
1234

References