What kind of type conversion is supported by Go?

Go supports various types of type conversions to convert values from one type to another. The supported type conversions in Go include:

  1. Numeric Type Conversions: Go allows you to convert between numeric types explicitly. For example:
var x int = 10
var y float64 = float64(x) // Convert int to float64
  1. String Conversions: You can convert between strings and numeric types, as well as other types, using the appropriate functions or strconv package. For example:
var strInt = "123"
var intValue, err = strconv.Atoi(strInt) // Convert string to int

var floatValue = 3.14
var strFloat = strconv.FormatFloat(floatValue, 'f', -1, 64) // Convert float64 to string
  1. Rune Conversions: A rune is an alias for int32, and you can convert between rune and int32 explicitly.
var r rune = 'A'
var i int32 = int32(r) // Convert rune to int32
  1. Type Assertion: Type assertion allows you to extract the underlying value from an interface type when you know its concrete type. It is commonly used when working with interface{} values.
var data interface{} = "Hello"
var str string = data.(string) // Type assertion to convert interface{} to string
  1. Pointer Type Conversion: You can convert a pointer of one type to a pointer of another type as long as the underlying types are compatible.
var x int = 42
var ptrX *int = &x
var ptrFloat *float64 = (*float64)(unsafe.Pointer(ptrX)) // Convert *int to *float64 (unsafe)

It’s essential to note that not all type conversions are possible in Go. The type conversion must be allowed and make sense based on the underlying types involved. When performing type conversions, be mindful of potential data loss, precision issues, or unexpected behaviors, especially when converting between numeric types.

Additionally, the unsafe package allows for unsafe pointer type conversions, but its usage should be avoided unless necessary, as it can lead to undefined behavior and compromise safety.

error: Content is protected !!