Implicit Type Conversion in Go
Implicit type conversion, commonly known as coercion, is the compiler's automated type conversion. Coercion is permitted or even required in several languages.
Because of its powerful type system, Golang does not support implicit type conversion.
Explicit Type Conversion in Go
In a given expression, explicit type conversion is a particular programming command that defines what data type a variable (or an intermediate computation result) should be treated as. Casting, for example, will exclude "additional" information (but never adds information to the type being cast).
Example: Go float to int conversion
package main
import "fmt"
func main() {
var floatValue float32 = 10.65
// type conversion from float to int
var intValue int = int(floatValue)
fmt.Printf("Float Value: %g\n", floatValue)
fmt.Printf("Integer Value: %d", intValue)
}
Output
Float Value: 10.65
Integer Value: 10
Example: Go int to float conversion
package main
import "fmt"
func main() {
var intValue int = 10
// type conversion from int to float
var floatValue float32 = float32(intValue)
fmt.Printf("Integer Value: %d\n", intValue)
fmt.Printf("Float Value: %f", floatValue)
}
Output
Integer Value: 10
Float Value: 10.000000
Example: Add int and float number using Go type casting
package main
import "fmt"
func main() {
var num1 int = 90
var num2 float32 = 8.7
var sum float32
// addition of different data types
sum = float32(num1) + num2
fmt.Printf("Sum is %g",sum)
}
Output
Sum is 98.7
FAQs
-
How do you convert types of Go?
The strconv.Itoa method from the strconv package in the Go standard library can be used to convert numbers to strings. If you enter a number or a variable into the method's parenthesis, the numeric value is converted to a string value.
-
What is type assertion in Golang?
In Golang, type assertions provide access to the actual type of a variable in an interface. If the data type is already present in the interface, it will obtain the interface's real data type value. A type assertion pulls a value of the provided explicit type from an interface value.
-
How do I change variable type in Golang?
Because Go is a statically typed language, the types of variables must be known at build time, and they cannot be changed at runtime.
Key Takeaways
In this article we have extensively discussed typecasting and its implementation in GoLang. We saw how typecasting is done in Golang with the help of examples.
We hope that this blog has helped you enhance your knowledge regarding typecasting and if you would like to learn more, check out our articles on Typecasting in C.
Don’t stop here, explore Golang with Golang Archives from coding ninjas. Do upvote our blog to help other ninjas grow. Happy Coding!”