English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statements

Golang functions & methods

Golang structs

Golang slices & arrays

Golang strings(String)

Golang pointers

Golang interfaces

Golang concurrency

Golang exceptions(Error)

Golang other items

Go Type Conversion

Prerequisites, you should have learned:Golang data types

Type conversion occurs when we assign a value of one data type to another data type. Such as C / C ++Static type languages like Java provide support for implicit type conversion, but Golang is different because even if the data types are compatible, itis not supportedAutomatic type conversion or implicit type conversion. The reason is that Golang's strong type system does not allow this. Explicit conversion must be performed for type conversion.

How does Golang perform type conversion?
If you need to use some features of the data type hierarchy, then we must convert the entity from one data type to another. The general syntax for converting a value val to type T is T(val).

var w3codebox1 int = 845
// Explicit type conversion
var w3codebox2 float64 = float64(w3codebox1)
var w3codebox3 int64 = int64(w3codebox1)
var w3codebox4 uint = uint(w3codebox1)
//Calculate the average
package main
import "fmt"
func main() {
    var totalsum int = 446
    var number int = 23
    var avg float32
    // Explicit type conversion
    avg = float32(totalsum) / float32(number)
    // Display the result
    fmt.Printf("Average = %f\n", avg)
}

Output:

Average = 19.391304

Note:Due to the strong type system of Golang, it does not allow the use of mixed numeric types (such as addition, subtraction, multiplication, division, etc.) in expressions, and does not allow type assignment between two mixed types.

var w3codebox1 int64 = 875
//It will throw an error to us at compile time
//because we are performing mixed type operations, for example, adding int64as int type
var w3codebox2 int = w3codebox1
var w3codebox3 int = 100
//It throws a compile-time error
//This is an invalid operation
//because the type is mixed int64 and int addition
var addition = w3codebox1 + w3codebox3