Open rodriggj opened 2 years ago
int
, the other is a decimal which is typed as float64
. package main
import (
"fmt"
)
func main() {
speed := 5 //speed is currently typed as an int
force := 2.5 //force is currenlty typeda as float64
speed = speed * force
fmt.Println("speed:", speed)
}
The VS Code will emit an error, because there is a type mismatch.
type mismatch
you have 2 choices. 1. you can cast speed to another data type or 2. you can cast force to another data type. First try to cast force
to an int...
func main() {
speed := 5 //speed is currently typed as an int
force := 2.5 //force is currenlty typeda as float64
speed = speed * int(force)
fmt.Println("speed:", speed)
}
Results in ...
NOTE: The standard rounding logic of the next integer if greater than 5 will round the value upward DOES NOT apply and therefore float conversion can be a DESTRUCTIVE OPERATION. In this case 2.5 does not round to 3, it simply remains at int value of 2 and the decimal precision is LOST.
NOTE: If you want to see this conversion happen, add an additional line to the code
fmt.Println("force", int(force))
package main
import (
"fmt"
)
func main() {
speed := 5 //speed is currently typed as an int
force := 2.6 //force is currenlty typeda as float64
speed = float64(speed) * force
fmt.Println("speed:", speed)
}
speed
is still an int even though it has been cast as a float64. So casting to a float doesn't work. Instead you simply need to change the value of speed to 5.0package main
import (
"fmt"
)
func main() {
speed := 5.0 //speed is currently typed as an int
force := 2.6 //force is currenlty typeda as float64
speed = speed * force
fmt.Println("speed:", speed)
}
Results in ...
package main
import ( "fmt" )
func main() { speed := 5 //speed is currently typed as an int force := 2.6 //force is currenlty typeda as float64
speed = int(float64(speed) * force)
fmt.Println("speed:", speed)
}
Which also results in 13.
Type Conversion
The type conversion express is like this: