

Go Type casting - conversion
Type cast or conversion is a way of changing an object from one data type to another. It is used in computer programming to ensure a function handles the variables correctly. Go does support type casting by using below syntax form:type_name(expression)
Example of Go Type casting - conversion
package main
import "fmt"
func main() {
var value1 int = 22
var value2 int = 5
var value3 float32
value3 = float32(value1)/float32(value2)
fmt.Printf("Value of value3 : %f\n",value3)
}
Output
Value of value3 : 4.400000
Example of Go Type casting - conversion using strconv.FormatInt
Below is an example of typecasting from integer to String using strconv.FormatInt()package main
import (
"fmt"
"strconv"
)
func main() {
var value1 int = 22
value2 := strconv.FormatInt(int64(value1), 10)
isString := value2 == "22"
fmt.Printf("is type cast from int to string working: ", isString)
}
Output
is type cast from int to string working: %!(EXTRA bool=true)
Example of Go Type casting - conversion using strconv.Itoa
Below is an example of typecasting from integer to String using strconv.Itoa()package main
import (
"fmt"
"strconv"
)
func main() {
var value1 int = 22
value2 := strconv.Itoa(value1)
isString := value2 == "22"
fmt.Printf("is type cast from int to string working: ", isString)
}
Output
is type cast from int to string working: %!(EXTRA bool=true)
Conclusion
In this page (written and validated by A. Gawali) you learned about Go Type casting - conversion . What's Next? If you are interested in completing Go tutorial, your next topic will be learning about: Go Concatenate two strings.
Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.
Share On: |
Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.