Golang Type Conversions
Converting from one datatype to another is a frequent task we programmers do. Let’s dig around how type conversions work in Go.
Let me go and tell you how this article is going to be structured.
- General syntax of Type Conversions.
- Type Conversion from string to int/int64, int/int64 to string
General syntax of Type Conversions
If you have to convert a value from one datatype to another, then you have to follow the following syntax -
newDataTypeVariable = T(oldDataTypeVariable)
where T is the new data type.
Some numeric conversions:
var i int = 22
var floatVar = float64(i)
var uIntVar = uint(floatVar)
Unlike in C, in Go assignment between items of different type requires an explicit conversion. Try removing the float64
or uint
conversions in the example and see what happens.
Type Conversion from string to int/int64, int/int64 to string
To convert from string to int, int to string and int to int64 you need separate package imported in the go file which is “strconv”. Check out strconv.
To convert from string to int, the function to use is Atoi shown as below :-
var s string = "1234"
i,_ := strconv.Atoi(s)
fmt.Println(i) //1234
fmt.Println(reflect.TypeOf(i)) //int
Note: the Atoi function returns 2 values, one is the converted value and other is of type error.
To convert from int to string, the function to use is Itoa as below :-
var i int = 1234
s := strconv.Itoa(i)
fmt.Println(s) //1234
fmt.Println(reflect.TypeOf(s)) //string
To convert from int64 to string, the function to use is FormatInt as below :-
var i int64 = 1234
s := strconv.FormatInt(i, 10)
fmt.Println(s) //1234
fmt.Println(reflect.TypeOf(s)) //string
Note: 10 in the FormatInt function simply specifies the decimal value…