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)
}
i
&c
are untyped constants that allow implicit conversion. Doesi
andc
have implicit conversion tofloat64
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)
}
- Is
string(97)
a type conversion or type casting? Becausestring(97)
is giving"a"
but not"97"
, which is type casting based on this answer
CodePudding user response:
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
.