Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go – Type conversion vs Type casting

In the below code for type conversion:

package main

import "fmt"

const c = 3.2
const i = 3

func main() {
    var f float64 = i * c // implicit conversion of i
    fmt.Println(f)
}

  1. i & c are untyped constants that allow implicit conversion. Does i and c have implicit conversion to float64 before performing multiplication?

Below code supposed to demonstrate type casting:

package main

import "fmt"

func main() {
    // s := string(97) // works fine, but, Is this type conversion or type casting?
                      // because below line gives error - "cannot convert 97.2 (type untyped float) to type string"
    s := string(97.2)
    fmt.Println(s)
}

  1. Is string(97) a type conversion or type casting? Because string(97) is giving "a" but not "97", which is type casting based on this answer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the following, the multiplication of constants is done in compile time, then the result is converted to float and stored in f as float64. There is no type conversion at runtime.

    var f float64 = i * c 

The following is not valid Go code, so it is not conversion or casting.

    s := string(97.2)

There is no type-casting in Go.

If you did:

s:=int(f)

where f is float, that is a type conversion where the value of f is converted to int and assigned to s.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading